LoginSignup
22
20

More than 5 years have passed since last update.

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

Posted at

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

22
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
20