Java6で動いた。
ソースコード抜粋。


public static void main(String[] args) throws Exception {
  HttpBasicAuthenticator hba = new HttpBasicAuthenticator("username", "password");
  Authenticator.setDefault(hba);
}
 
public static class HttpBasicAuthenticator extends Authenticator {
  private String username;
  private String password;
  public HttpBasicAuthenticator(String username, String password) {
    this.username = username;
    this.password = password;
  }
  protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username, password.toCharArray());
  }
  public String myGetRequestingPrompt() {
    return super.getRequestingPrompt();
  }
}

他の方法としてはHTTPリクエストヘッダを直接なんとかするとか。それにしても Authenticator.setDefault ってなんで static メソッドなんだろう。他に何かまともな方法がありそうな気がするけど、もう調べる気力がない。。。

Ref. Java で HTTP クライアントを作ってみよう (3)

tags: Java zurazure

Posted by NI-Lab. (@nilab)