「Yahoo!デベロッパーネットワーク」の「関連検索ワードWebサービス」を Jakarta Commons HttpClient から利用してみるサンプル。

Jakarta Commons HttpClient の下準備

必要なライブラリ: Jakarta Commons HttpClientJakarta Commons Codec をダウンロードしてきて、
commons-httpclient-3.0.1.jar と commons-codec-1.3.jar をクラスパスに通す。
もしかしたら Commons Logging も要るかも。
このあたりのことが、どのドキュメントに書かれているか見つからない……リリースノートにチラっとあったぐらい?

関連検索ワードWebサービスの下準備

Yahoo! JAPAN ID を取得して、アプリケーションIDを登録する。
Yahoo!デベロッパーネットワーク - アプリケーションIDを登録

ソースコード


import java.net.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
 
/**
 * 「Yahoo!デベロッパーネットワーク」 の 「関連検索ワードWebサービス」 を
 * Jakarta Commons HttpClient から利用してみるサンプル。
 * 
 * Ref. Yahoo!デベロッパーネットワーク - Yahoo!検索 - 関連検索ワード
 *    http://developer.yahoo.co.jp/search/webunit/V1/webunitSearch.html
 */
public class YahooWebunitSearch {
 
  public static void main(String[] args) throws Exception {
    YahooWebunitSearch yws = new YahooWebunitSearch("YahooDemo");
    yws.search("猫", null, null);
  }
 
  private static final String base = "http://api.search.yahoo.co.jp/AssistSearchService/V1/webunitSearch";
  private final String appid;
  
  /**
   * @appid アプリケーションID
   */
  public YahooWebunitSearch(String appid){
    this.appid = appid;
  }
 
  public void search(String query, String results, String start) throws Exception {
 
    String p_query = URLEncoder.encode(query, "UTF-8");
    String p_results = normalizeIntegerString(results);
    String p_start = normalizeIntegerString(start);
    
    StringBuffer url = new StringBuffer(base);
    url.append("?appid=" + appid);
    url.append("&query=" + p_query);
    if(p_results != null){
      url.append("&results=" + p_results);
    }
    if(p_start != null){
      url.append("&start=" + p_start);
    }
 
    System.out.println(url.toString());
 
    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    GetMethod get = new GetMethod(url.toString());
    get.setFollowRedirects(true);
    int iGetResultCode = client.executeMethod(get);
    final String strGetResponseBody = get.getResponseBodyAsString();
    System.out.println(strGetResponseBody);
  }
 
  private String normalizeIntegerString(String s){
    try{
      if(s != null){
        return "" + Integer.parseInt(s);
      }else{
        return null;
      }
    }catch(Exception e){
      return null;
    }
  }
 
}

実行結果


http://api.search.yahoo.co.jp/AssistSearchService/V1/webunitSearch?appid=YahooDemo&query=%E7%8C%AB
2007/01/05 20:19:18 org.apache.commons.httpclient.HttpMethodBase getResponseBody
警告: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
<?xml version="1.0" encoding="UTF-8" ?>
<ResultSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:yahoo:jp:srchunit" xsi:schemaLocation="urn:yahoo:jp:srchunit http://api.search.yahoo.co.jp/AssistSearchService/V1/WebUnitSearchResponse.xsd" totalResultsReturned="10" totalResultsAvailable="100" firstResultPosition="1">
<Result>ペット 猫</Result>
<Result>猫 里親</Result>
<Result>犬 猫</Result>
<Result>猫 病気</Result>
<Result>猫 画像</Result>
<Result>猫 写真</Result>
<Result>猫 壁紙</Result>
<Result>猫 ブログ</Result>
<Result>猫 イラスト</Result>
<Result>猫 種類</Result>
</ResultSet>
<!-- pls338.search.tnz.yahoo.co.jp uncompressed/chunked Fri Jan  5 20:19:18 JST 2007 -->
<!-- ws2.search.bbt.yahoo.co.jp uncompressed/chunked Fri Jan  5 20:19:18 JST 2007 -->

2~3行目は標準エラー出力。


2007/01/05 20:19:18 org.apache.commons.httpclient.HttpMethodBase getResponseBody
警告: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

getResponseBodyAsStream 使ったほうがいいよ、って。

# HttpClientJakarta Commons HttpClient が使いにくそうな予感……

Jakarta Commons Codec が無いときのエラー

commons-codec-1.3.jar がクラスパスに無いときは、こんな感じで怒られる。


Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/codec/DecoderException
  at org.apache.commons.httpclient.HttpMethodBase.<init>(HttpMethodBase.java:217)
  at org.apache.commons.httpclient.methods.GetMethod.<init>(GetMethod.java:88)
  at YahooWebunitSearch.search(YahooWebunitSearch.java:52)
  at YahooWebunitSearch.main(YahooWebunitSearch.java:22)

Ref.

tags: zlashdot Java Java

Posted by NI-Lab. (@nilab)