HttpClientを使ってみる

ヤフオクAPIにアクセスする仕事ができたので、JavaでRESTするAPIを探してみた。

Restletってのがわりと良いらしい。
http://www.restlet.org/


けど今回はわりと急ぎなので、使い慣れたHttpClientとXstreamで実装することにしよう。
まぁRestletも中身ではHttpClientを使ってるみたいだしいいか。


というわけでHttpClientのメモ。

まずはダウンロード。
http://hc.apache.org/downloads.cgi
なんか新しいのが増えてるけど、今回は気にせず、
Commons HttpClient 3.1をダウンロード。

commonsのcodecとloggingも必要なのでダウンロード。
http://commons.apache.org/downloads/download_codec.cgi
http://commons.apache.org/downloads/download_logging.cgi


そしてダウンロードした3つのjarにクラスパスを通して準備完了。


コードはこんな感じ。

public static void main(String[] args) {
    String url = "http://auctions.yahooapis.jp/AuctionWebService/V1/SellingList?"
            + "appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
            + "&sellerID=the_longbows";
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);

    try {
        int executeMethod = client.executeMethod(method);
        if (executeMethod == HttpStatus.SC_OK) {
            String body = method.getResponseBodyAsString();
            System.out.println(body);
        }

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
}

これは簡単。


ちなみに、本番ではgetResponseBodyAsString()じゃなくてgetResponseBodyAsStream()を使うべき。