INDEX
HTTP認証
HttpURLConnection による接続で、Basic認証 および Digest認証を行う。
Authenticator を継承したクラスを作成し、ユーザ認証が要求されたときにユーザ情報( PasswordAuthentication )を返すようにする。ユーザ認証の要求時にユーザに入力させる場合は、Authenticator#getPasswordAuthentication() でダイアログなどを表示する。URLConnection で対象サーバに接続する前に Authenticator#setDefault() で作成した Authenticator をセットしておく。
しかし、まぁ、なんでこんな作りなんだろうか? Authenticator#setDefault が static メソッドなので、マルチスレッド環境でサーバやページによって認証情報を変えたい場合とかどうするんでしょう…。あと、失敗時のリトライ回数を指定できないのだろうか…。
HTTPユーザー認証処理
デフォルトコンストラクタでユーザ情報を指定して認証処理を行うようにする。
1 |
import java.net.Authenticator;
import java.net.PasswordAuthentication;
/**
* HTTPユーザー認証処理クラス.
*/
public class HttpAuthenticator extends Authenticator {
/** ユーザ名 */
private final String username;
/** パスワード */
private final String password;
/**
* 指定されたユーザ情報でHTTPユーザー認証処理オブジェクトを構築します。
* @param username ユーザ名
* @param password パスワード
*/
public HttpAuthenticator(String username, String password) {
if (username == null || password == null)
throw new IllegalArgumentException("username or password is null.");
this.username = username;
this.password = password;
}
/**
* 認証に使用するユーザ名を取得します。
* @return ユーザ名
*/
public String getUsername() {
return this.username;
}
/**
* 認証に使用するパスワードを取得します。
* @return パスワード
*/
public String getPassword() {
return this.password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//System.out.println("RequestingHost\t:" + getRequestingHost());
//System.out.println("RequestingSite\t:" + getRequestingSite());
//System.out.println("RequestingPort\t:" + getRequestingPort());
//System.out.println("RequestingProtocol\t:" + getRequestingProtocol());
//System.out.println("RequestingPrompt\t:" + getRequestingPrompt());
//System.out.println("RequestingScheme\t:" + getRequestingScheme());
//System.out.println("RequestingURL\t:" + getRequestingURL());
//System.out.println("RequestorType\t:" + getRequestorType());
//System.out.println("UserName/PassWord\t:" + this.username + "/" + this.password);
return new PasswordAuthentication(this.username, this.password.toCharArray());
}
} |
HTTPユーザー認証
// URLとID/PW
URL url = url = new URL("http://wwww.example.com/httpauth/secret.html");
String username = "hoge";
String password = "fuga";
// ユーザ認証情報の設定
HttpAuthenticator httpAuth = new HttpAuthenticator(username, password);
Authenticator.setDefault(httpAuth);
// 認証必要ページへ接続
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
conn.connect();
System.out.println();
System.out.println("Response: " + conn.getResponseCode() + " " + conn.getResponseMessage()); |
認証処理は20回リトライされる。それでも失敗する場合は、“401 Authorization Required”となる(JDK 1.5, 1.6)
参考
- Java で HTTP クライアントを作ってみよう (3) (68user's page)
最終更新時間:2010年09月02日 17時19分10秒 指摘や意見などあればSandBoxのBBSへ。