URLConnectionを使用する場合
Authenticator
の実装クラスを作成してユーザー名とパスワードを設定する。
少し古い情報だとシステムプロパティのproxyUser
とproxyPassword
を使うように書いてあるが、現在は使用できないので注意。
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