Skip to content

Instantly share code, notes, and snippets.

@iwazer
Created May 20, 2011 01:21
Show Gist options
  • Save iwazer/982162 to your computer and use it in GitHub Desktop.
Save iwazer/982162 to your computer and use it in GitHub Desktop.
JavaでBasic認証(ただしマルチスレッドなサーバでは使えない…)
import java.net.Authenticator;
import java.net.PasswordAuthentication;
// Basic認証のAuthenticatorを作成
class HttpAuthenticator extends Authenticator {
public String username;
public String password;
public HttpAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
}
// 使う
HttpAuthenticator httpAuth = new HttpAuthenticator(user, pass);
Authenticator.setDefault(info.httpAuth);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
conn.connect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment