Reading URLs Protected with HTTP Authentication : Web Server Client : Network Protocol : Java examples (example source code) Organized by topic

Java
C++
PHP
Java Home »  Network Protocol   » [  Web Server Client  ]  Screenshots 
 



Reading URLs Protected with HTTP Authentication


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;

public class AuthDemo {
  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 = (InputStreamurl.getContent();
    BufferedReader in = new BufferedReader(new InputStreamReader(content));
    String line;
    while ((line = in.readLine()) != null) {
      System.out.println(line);
    }
    System.out.println("Done.");
  }

  static 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());
    }
  }
}
           
       
Related examples in the same category
1.  Connect with a Web server Connect with a Web server
2.  Reading Web Pages with Streams Reading Web Pages with Streams
3.  Reading Web Pages, with Socket Channels Reading Web Pages, with Socket Channels
4.  Reading Web Pages with Nonblocking Channels Reading Web Pages with Nonblocking Channels
5.  A Simple Web Server A Simple Web Server
6.  HTML Post
7.  Thread Unsynch
8.  Web serverHas Download File
9.  Save binary file from web