Javaで各種WebのAPIにRESTするのに一番簡単な方法は?

いろんな手段がありえるが、今回は「Restlet」を取り上げてみる。
Restlet自体はAPIを提供する側のサーバ機能を利用することが多いようですが、今回はあえてクライアントとして利用します。

まずは、Restletのライブラリをダウンロードする。
Restlet - Downloads

Zip archive版の中から、

com.noelios.restlet.jar
org.restlet.jar
com.noelios.restlet.ext.httpclient_3.1.jar

を取り出し、CLASSPATHに通す。

そして、commonsプロジェクトにも依存しているようなので、
Apache Commons - Logging Downloads

Apache Commons - Codec Downloads

HttpClient - HttpClient Downloads

から、それぞれ

commons-logging-1.1.jar
commons-codec-1.3.jar
commons-httpclient-3.1.jar

を取り出し、CLASSPATHに通す。

さて、今日はどのAPIを標的とするかというと、、東京大学空間情報科学研究センターが提供する、住所から位置情報を割り出せるというCSISシンプルジオコーディングを利用してみようと思う。

さっそくコードはこんな感じに。東京都渋谷区道玄坂をターゲットにしてみました。

JAVA:
  1. import org.restlet.Client;
  2. import org.restlet.data.Protocol;
  3. import org.restlet.data.Reference;
  4. import org.restlet.resource.DomRepresentation;
  5. import org.w3c.dom.Node;
  6.  
  7. public class Main {
  8.  
  9.     public static void main(String[] args) {
  10.         try {
  11.             Client client = new Client(Protocol.HTTP);
  12.             String url = "http://geocode.csis.u-tokyo.ac.jp/cgi-bin/simple_geocode.cgi"
  13.                 + "?addr=" + Reference.encode("東京都渋谷区道玄坂")
  14.                 + "&charset=UTF8";
  15.             DomRepresentation xml = client.get(url).getEntityAsDom();
  16.             Node n1 = xml.getNode("//results/candidate/address");
  17.             System.out.println("address : " + n1.getTextContent());
  18.             Node n2 = xml.getNode("//results/candidate/longitude");
  19.             System.out.println("longitude : " + n2.getTextContent());
  20.             Node n3 = xml.getNode("//results/candidate/latitude");
  21.             System.out.println("latitude : " + n3.getTextContent());
  22.            
  23.         } catch (Exception e) {
  24.             e.printStackTrace();
  25.         }
  26.     }
  27. }

実行結果はこちら

address : 東京都/渋谷区/道玄坂
longitude : 139.698166
latitude : 35.657429

Clientのインスタンスを作って、URLを書き、そして簡単にxmlの解析ができます。超簡単!
なんといっても、ソースが直感的。
ライブラリの依存関係がうざいけど、シンプルなAPIにはかなり使えそうだ。

そして、このシンプルジオコーディング、かなりつかえるぞ!
住所の文字列から住所の区分けまでやってくれます。さすが。

関連する記事

blogranking←ぽちっとな

<<
>>