3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Apache httpclient の CloseableHttpClient で HTTPS なサイトへ BASIC 認証付きリクエスト

Last updated at Posted at 2016-12-02

日本語情報がぱっと見無かったので、自分用メモも兼ねて。
エラー処理とかが雑なのは適宜補完していただければ。

sample.java
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Main {
    public static void main(String[] args){
        // パラメータ
        String host = "ホスト名";
        String path = "パス";
        String username = "ユーザ名";
        String password = "パスワード";

        // 認証情報の設定
        HttpHost httpHost = new HttpHost(host,443,"https");
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(httpHost.getHostName(),httpHost.getPort()),
                new UsernamePasswordCredentials(username, password));

        // CloseableHttpClient のインスタンス作成 作成時に認証情報を追加する。
        closeableHttpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();

        try {
            // GET する URL を指定
            HttpGet httpGet = new HttpGet("https://" + host + path);
            // リクエストを実行してレスポンスを取得
            CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);

            // レスポンスのBODYを取得
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            System.out.println(EntityUtils.toString(httpEntity));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

「HTTPS なサイトへ」と書きましたが、HTTP の時と殆ど処理内容は変わりないです。scheme を変えるくらい。
stackoverflow の回答とか見ると SSLConnectionSocketFactory 作ったりしてますけど、無くても動くんですよねぇ…、謎。

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?