Accessing a Password-Protected URL - Java Network

Java examples for Network:URL

Description

Accessing a Password-Protected URL

Demo Code


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;

public class Main {
  public static void main(String[] argv) {
    Authenticator.setDefault(new MyAuthenticator());

    try {/*  w w  w.  j  ava 2 s  .  co m*/
      URL url = new URL("http://hostname:80/index.html");

      BufferedReader in = new BufferedReader(new InputStreamReader(
          url.openStream()));
      String str;
      while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
      }
      in.close();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }
  }

}

class MyAuthenticator extends Authenticator {
  protected PasswordAuthentication getPasswordAuthentication() {
    // Get information about the request
    String promptString = getRequestingPrompt();
    String hostname = getRequestingHost();
    InetAddress ipaddr = getRequestingSite();
    int port = getRequestingPort();

    // Get the username from the user...
    String username = "myusername";

    // Get the password from the user...
    String password = "mypassword";

    // Return the information
    return new PasswordAuthentication(username, password.toCharArray());
  }
}

Related Tutorials