RestletのEdition for Androidを使ってみた
AndroidでRESTで通信するモジュールがあったので、試してみました。Jsonのパーサもあるみたいです。
・Restlet Edition for Androidをダウンロード
Restletのダウンロードページから、2.0の「Available editions」→「Edition for Android」の「Zip archive」からダウンロードします。
・使用するjarを取り込む
ダウンロードしたzipを解凍し、「/lib/」ディレクトリ内にある、「org.restlet.jar」と「org.restlet.ext.json.jar」をAndroidプロジェクトのassets内に入れ、プロジェクトを右クリック→プロパティ→ビルドパス→ライブラリ→jarの追加から、上記の2つのjarを取り込む。
・GET通信
import org.restlet.Client;
import org.restlet.Request;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
(中略)
Client client = new Client(Protocol.HTTP);
String url = "http://www.example.com/";
Request request = new Request(Method.GET, url);
try {
String jsonStr = client.handle(request).getEntity().getText();
JsonRepresentation json = new JsonRepresentation(jsonStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
・POST通信
import org.restlet.Client;
import org.restlet.Request;
import org.restlet.data.Form;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
(中略)
Client client = new Client(Protocol.HTTP);
String url = "http://www.example.com/";
Form form = new Form();
form.add("name", "value");
Representation rep = form.getWebRepresentation();
Request request = new Request(Method.POST, url, rep);
try {
String jsonStr = client.handle(request).getEntity().getText();
JsonRepresentation json = new JsonRepresentation(jsonStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
・参考
Restlet edition for Android
Restlet edition for Android – Sample application


