HttpComponents - Client の使い方メモ

昔はCommons http clientとか言われてましたが、HttpComponentsという形でCommonsから独立し、サーバ作ったりとかClient以外のことも色々できるようになったライブラリです。
http://hc.apache.org/

準備

HttpComponents-clientは、HttpComponentsで簡単にHTTP Clientを実装できる追加ライブラリになっています。必要なjarは以下の通りです。

  1. httpcore-4.0.1.jar
  2. httpclient-4.0-beta2
  3. commons-logging-1.1.1.jar
  4. commons-codec-1.3.jar (Base64エンコードなどに必要)

尚、Coreのみでもクライアントは実装できますし、マルチスレッドで投げたりハンドリング時に色々埋め込みたい場合など、clientは使わずに自分でクライアントを実装可能です。

get

とりあえずget

  DefaultHttpClient client = new DefaultHttpClient();
  HttpGet get = new HttpGet("http://www.example.com");
  String responseBody = httpClient.execute(get, new BasicResponseHandler());

post

ちょっと面倒だけどpost

  DefaultHttpClient client = new DefaultHttpClient();
  HttpPost post = new HttpPost("http://www.example.com/login");
  ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("user", user));
  params.add(new BasicNameValuePair("password", password));
  post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
  String responseBody = httpClient.execute(post, new BasicResponseHandler());

Basic認証

AuthScopeで認証を行う範囲を指定する

  DefaultHttpClient client = new DefaultHttpClient();
  client.getCredentialsProvider().setCredentials(
          AuthScope.ANY, new UsernamePasswordCredentials(user, passwd));