AuthenticatorTest.java

import java.net.*;
import java.io.*;
public class AuthenticatorTest extends Authenticator {
  private PasswordAuthentication authenticator;
  /** Constructeur stockant l'identificateur et le mot de passe
      à utiliser par défaut */
  public AuthenticatorTest(String name, String passwd) {
    authenticator = new PasswordAuthentication(name,passwd.toCharArray());
  }
  
  /** Méthode appelée chaque fois qu'un code de statut 401 ou 407
      est retourné. */
  public PasswordAuthentication getPasswordAuthentication() {
    // Affiche des informations concernant la requête
    // ayant entrainée l'appel du gestionnaire d'authentification
    System.out.println("Site: " + getRequestingSite());
    System.out.println("Port: " + getRequestingPort());
    System.out.println("Scheme: " + getRequestingScheme());
    System.out.println("Prompt: " + getRequestingPrompt());
    // Retourne l'identificateur et le mot de passe précisés au moment
    // de la construction
    return authenticator;
  }
  public static void main(String[] args) throws IOException {
    if (args.length!=1) {
      System.err.println("Usage: java AuthenticatorTest <url>");
      System.exit(1);
    }
    // Création d'un gestionnaire d'authentification
    AuthenticatorTest auth;
    auth = new AuthenticatorTest("Frodon","l'anneau unique");
    // Installation du gestionnaire d'authentification
    Authenticator.setDefault(auth);
    URL url = new URL(args[0]);
    URLConnection uc = url.openConnection();
    InputStream in = uc.getInputStream();
    int c;
    while ((c=in.read())!=-1) {
      System.out.println((char)c);
    }
  }
}