Posted at

Javaで認証が必要なProxyサーバー経由でHTTP接続する

More than 3 years have passed since last update.


URLConnectionを使用する場合

Authenticatorの実装クラスを作成してユーザー名とパスワードを設定する。

少し古い情報だとシステムプロパティのproxyUserproxyPasswordを使うように書いてあるが、現在は使用できないので注意。

    public static String URL = "http://www.apache.org/";

public static String HOST = "proxy.server";
public static int PORT = 9000;
public static String USER = "user";
public static String PASSWORD = "pass";

public static void example1() throws Exception {
System.setProperty("proxySet", "true");
System.setProperty("proxyHost", HOST);
System.setProperty("proxyPort", Integer.toString(PORT));

Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USER, PASSWORD.toCharArray());
}
});

URL url = new URL(URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
System.out.println(conn.getResponseCode());
}


HttpClient4.3を使用する場合

    public static void example2() throws Exception {

HttpHost proxy = new HttpHost(HOST, PORT);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(proxy),
new UsernamePasswordCredentials(USER, PASSWORD));
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setDefaultRequestConfig(config)
.build();

HttpGet get = new HttpGet(URL);
HttpResponse res = httpclient.execute(get);
System.out.println(res.getStatusLine());
}


参考

Apache HttpComponents > HttpClient 4.3 > Examples > Proxy authentication