Home > Java > JavaのHttpClient 4 を触ってみた。

JavaのHttpClient 4 を触ってみた。

  • Posted by: sinsengumi
  • 2010年10月7日 11:30 AM
  • Java
  • |

HttpClientの3.0系はレガシーということで、4系を触ってみました。
実行環境は以下です。

  • JRE 1.6
  • HttpClient 4.0.3 (httpclient-4.0.3.jar)
  • HttpCore 4.0.1 (httpcore-4.0.1.jar)
  • Commons Logging 1.1.1 (commons-logging-1.1.1.jar)

簡単に、HTTP接続ができていい感じです。

サンプルは以下。

public class HTTPSample {

    private static HttpClient httpClient = new DefaultHttpClient();

    public static void main(String[] args) {

        // プロキシがある場合は、以下のようにして設定する
        //HttpHost proxy = new HttpHost("XXX.XXX.XXX.XXX", 8080);
        //httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        Map<String, String> requestParams = new HashMap<String, String>();
        requestParams.put("pattern", "ltrim");
        requestParams.put("lang", "ja");

        httpGet("http://jp2.php.net/manual-lookup.php", requestParams);
        // httpPost("http://jp2.php.net/manual-lookup.php", requestParams);

        // HTTP接続を閉じる(shutdownを実行するとセッションが切れます)
        httpClient.getConnectionManager().shutdown();
    }

    private static void httpGet(String url, Map<String, String> requestParams) {

        HttpGet httpGet = null;

        try {
            // リクエストパラメータの設定
            StringBuilder builder = new StringBuilder(url);
            builder.append("?");
            for (Map.Entry<String, String> entry : requestParams.entrySet()) {
                builder.append((String) entry.getKey());
                builder.append("=");
                builder.append((String) entry.getValue());
                builder.append("&");
            }

            String tmpUrl = builder.toString();
            tmpUrl = tmpUrl.substring(0, tmpUrl.length() - 1);

            httpGet = new HttpGet(tmpUrl);

            System.out.println("executing request " + httpGet.getURI());
            System.out.println("-------------------------------------");

            HttpResponse response = httpClient.execute(httpGet);

            // レスポンスヘッダーの取得
            System.out.println(response.getStatusLine().getStatusCode());

            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                System.out.println(header.getName() + ": " + header.getValue());
            }

            System.out.print(System.getProperty("line.separator"));

            // レスポンスボディの取得
            HttpEntity httpEntity = response.getEntity();
            System.out.println(EntityUtils.toString(httpEntity));

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpGet != null) {
                httpGet.abort();
            }
        }
    }

    private static void httpPost(String url, Map<String, String> requestParams) {

        HttpPost httpPost = null;

        try {
            // リクエストパラメータの設定
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : requestParams.entrySet()) {
                params.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue()));
            }

            httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

            System.out.println("executing request " + httpPost.getURI());
            System.out.println("-------------------------------------");

            // レスポンスヘッダーの取得
            HttpResponse response = httpClient.execute(httpPost);
            System.out.println(response.getStatusLine().getStatusCode());

            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                System.out.println(header.getName() + ": " + header.getValue());
            }

            System.out.print(System.getProperty("line.separator"));

            // レスポンスボディの取得
            HttpEntity httpEntity = response.getEntity();
            System.out.println(EntityUtils.toString(httpEntity));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpPost != null) {
                httpPost.abort();
            }
        }
    }
}

参考

Comments:0

Comment Form
Remember personal info

Trackbacks:0

Trackback URL for this entry
http://sinsengumi.net/blog/2010/10/java%e3%81%aehttpclient-4-%e3%82%92%e8%a7%a6%e3%81%a3%e3%81%a6%e3%81%bf%e3%81%9f%e3%80%82/trackback/
Listed below are links to weblogs that reference
JavaのHttpClient 4 を触ってみた。 from sinsengumi血風録

Home > Java > JavaのHttpClient 4 を触ってみた。

Search
Feeds
Meta

Return to page top