Read URLs Protected with HTTP Authentication in Java

Description

The following code shows how to read URLs Protected with HTTP Authentication.

Example


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
/*from  ww  w  .  j  a va  2s. co  m*/
public class Main {
  public static void main(String args[]) throws MalformedURLException,
      IOException {
    String urlString = "";
    String username = "";
    String password = "";
    Authenticator.setDefault(new MyAuthenticator(username, password));
    URL url = new URL(urlString);
    InputStream content = (InputStream) url.getContent();
    BufferedReader in = new BufferedReader(new InputStreamReader(content));
    String line;
    while ((line = in.readLine()) != null) {
      System.out.println(line);
    }
    System.out.println("Done.");
  }

}

class MyAuthenticator extends Authenticator {
  private String username, password;

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

  protected PasswordAuthentication getPasswordAuthentication() {
    System.out.println("Requesting Host  : " + getRequestingHost());
    System.out.println("Requesting Port  : " + getRequestingPort());
    System.out.println("Requesting Prompt : " + getRequestingPrompt());
    System.out.println("Requesting Protocol: " + getRequestingProtocol());
    System.out.println("Requesting Scheme : " + getRequestingScheme());
    System.out.println("Requesting Site  : " + getRequestingSite());
    return new PasswordAuthentication(username, password.toCharArray());
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Network »




NetworkInterface
URI
URL
HTTP
HTTP Read
IP
Socket
UDP
URL Encode