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シンプルジオコーディングを利用してみようと思う。
さっそくコードはこんな感じに。東京都渋谷区道玄坂をターゲットにしてみました。
-
import org.restlet.Client;
-
import org.restlet.data.Protocol;
-
import org.restlet.data.Reference;
-
import org.restlet.resource.DomRepresentation;
-
import org.w3c.dom.Node;
-
-
public class Main {
-
-
try {
-
Client client = new Client(Protocol.HTTP);
-
String url = "http://geocode.csis.u-tokyo.ac.jp/cgi-bin/simple_geocode.cgi"
-
+ "&charset=UTF8";
-
DomRepresentation xml = client.get(url).getEntityAsDom();
-
Node n1 = xml.getNode("//results/candidate/address");
-
Node n2 = xml.getNode("//results/candidate/longitude");
-
Node n3 = xml.getNode("//results/candidate/latitude");
-
-
e.printStackTrace();
-
}
-
}
-
}
実行結果はこちら
address : 東京都/渋谷区/道玄坂
longitude : 139.698166
latitude : 35.657429
Clientのインスタンスを作って、URLを書き、そして簡単にxmlの解析ができます。超簡単!
なんといっても、ソースが直感的。
ライブラリの依存関係がうざいけど、シンプルなAPIにはかなり使えそうだ。
そして、このシンプルジオコーディング、かなりつかえるぞ!
住所の文字列から住所の区分けまでやってくれます。さすが。


