Commons HttpClient

仕事で Java Web アプリケーションサーバから Web サービスを叩いてみるということで、HTTP クライアントをどうしようかと考えた。
プロキシ認証とかリトライとかタイムアウトとか色々ありそうなので Jakarta Commons HttpClient を試してみた。せっかくなので、Amazon Web Service を触ってみる。
screenshot
http://jakarta.apache.org/commons/httpclient/

package sample;

import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 * @author tosshi
 */
public class Main {

  /**
   * @param args
   */
  public static void main(String[] args) {
    HttpClient client = new HttpClient();

    // ソケットタイムアウトは 1秒
    client.getParams().setParameter("http.socket.timeout",
        new Integer(1000));

    /* 
     * プロキシの認証が必要なとき
     * 
     * Credentials cred = new UsernamePasswordCredentials("PROXYAUTHID", "PROXYAUTHPASS");
     * HttpState state = new HttpState();
     * state.setProxyCredentials(AuthScope.ANY, cred);
     * client.setState(state);
     */

    // URIを指定して GET を生成
    GetMethod method = new GetMethod("http://webservices.amazon.co.jp/onca/xml");
    
    // リトライは3回
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
        new DefaultHttpMethodRetryHandler(3, false));

    // クエリをセット
    NameValuePair[] pairs = {
        new NameValuePair("Service", "AWSECommerceService"),
        new NameValuePair("AWSAccessKeyId", ☆取得したAWSのアクセスキーID☆),
        new NameValuePair("Operation", "ItemSearch"),
        new NameValuePair("SearchIndex", "Music"),
        new NameValuePair("ResponseGroup", "Small"),
        new NameValuePair("Artist", "BENNIE K"),
    };
    
    method.setQueryString(pairs);

    try {
      // 実行
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // レスポンスをアウト
      InputStreamReader isr = new InputStreamReader(
                   method.getResponseBodyAsStream(), method.getResponseCharSet());
      
      final int BUFFER_SIZE = 1024;
      char[] buffer = new char[BUFFER_SIZE];
      int readSize;
      while ((readSize = isr.read(buffer, 0, BUFFER_SIZE)) > 0) {
        System.out.print(new String(buffer, 0, readSize));
      }
      isr.close();
      
    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // 接続を解放
      method.releaseConnection();
    }
  }
}