Javaと情熱のあいだ

Play Frameworkはじめました

HttpClient 4.0-beta2を使う POST編

以前書いた、HttpClient 4.0-beta2を使うはGETメソッドでしたが今回はPOSTメソッドを使用。
サンプルは、Hatena exist APIの結果を取得するものです。


材料はこちら
HttpCore 4.0 (GA)
HttpClient 4.0-beta2
Commons Logging

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import main.java.ExampleInterface;

public class HttpPostExample {
    /**
     * URI
     */
    private static final String SUGGETS_URI =
        "http://d.hatena.ne.jp/exist";

    /**
     *
     * 実行
     * @throws Exception 例外
     */
    public void execute() throws Exception {
        final HttpClient client = new DefaultHttpClient();

        final HttpPost post = new HttpPost(SUGGETS_URI);

        final List <NameValuePair> params = new ArrayList <NameValuePair>();

        params.add(new BasicNameValuePair("mode", "xml"));

        params.add(new BasicNameValuePair("url", "http://www.yahoo.co.jp/"));

        post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

        final HttpResponse response = client.execute(post);

        System.out.println(response.getStatusLine());

        System.out.println(EntityUtils.toString(response.getEntity()));

        post.abort();
    }
}

実行結果はこちら

HTTP/1.1 200 OK
<?xml version="1.0"?>
<existxml>
  <count name="diary">1942</count>
  <count name="antenna">1</count>

</existxml>