3 Replies Latest reply: Sep 4, 2009 5:47 PM by DrClap RSS

    File contents under authorization

      I would like to write the program having the possibility to read the file which is under authorization. Consider I have a page www.mypage.com , in title page there is two input fields to enter username and password. After successfully entering username and password the user is redirected to www.mypage.com/myzone/ . If you would try to visit this url ( www.mypage.com/myzone/ ) you would be redirected to www.mypage.com . So, I would like to write program which could read the contents from www.mypage.com/myzone/ using my username and my password. I tried using this code:

      import java.net.*;
      import java.io.*;

      public class URLConnectionAuthReader {
      public static void main(String[] args) throws Exception {
      String username = "username";
      String password = "password";
      URL authurl = new URL("http://www.mypage.com/myzone/ ");

      Authenticator.setDefault(new MyAuthenticator(username, password));
      URLConnection ac = authurl.openConnection();
      BufferedReader in = new BufferedReader(
      new InputStreamReader(
      String inputLine;

      while ((inputLine = in.readLine()) != null)

      protected static class MyAuthenticator extends Authenticator {
      private String username, password;

      public MyAuthenticator(String user, String pwd) {
      username = user;
      password = pwd;

      protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(username, password.toCharArray());

      But I am always getting the contents of the url www.mypage.com/ but not of www.mypage.com/myzone/ as I wrote in code.
        • 1. Re: File contents under authorization
          You would use an Authenticator if you were getting an HTTP authentication-required response from the server. But that's not what you described in your scenario.

          First you have to send the same request which the signon page sends. It's probably a POST request, for example. Once you get a response, then you have to send the request for the URL which you want. Don't forget to help the server preserve its session, it will probably send cookies which you have to send back.

          You can use the Apache HttpClient to do all that if you don't want to learn a whole lot about the intricacies of the HTTP protocol.
          • 2. Re: File contents under authorization
            Thank youfor the answer.

            As you offered I used HttpClient. Now I am getting from page "Cookies are not enabled on your browser." You mentioned that I have to send back cookies. But I have no idea what to write in that cookie. I would be very thankful if you could some more words about it.
            • 3. Re: File contents under authorization
              You send back the cookie that the server sent in the first call, if I'm not mistaken. Do none of the examples show how that's done?