RESTライブラリ比較
JAX-RSの実装にはライブラリが必要。
JerseyやRestlet などいくつかライブラリがある。
各ライブラリの比較は以下のURLを参照。
http://www.ibm.com/developerworks/jp/web/library/wa-apachewink3/
クライアント
http://java6.blog117.fc2.com/blog-entry-72.html
Jerseyを使う場合
TestClient.java
1 |
package test; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; public class TestClient { public static void main ( String[] args ) throws Exception { MultivaluedHashMap<String, String> formParams = new MultivaluedHashMap<>(); formParams.putSingle("a", "100"); formParams.putSingle("b", "200"); String result = ClientBuilder.newClient() .target("http://localhost:8080") .path("test") .request(MediaType.TEXT_PLAIN) .get(String.class); System.out.println(result); result = ClientBuilder.newClient() .target("http://localhost:8080") .path("add") .path("add2") .request() .post(Entity.form(formParams), String.class); // .post(Entity.entity(formParams ,MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class); System.out.println(result); } } |
java.netを使う場合
1 |
package test; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class TestClient2 { public static void main(String[] args) throws Exception { get(); post(); } public static void get() throws Exception { String url = "http://localhost:8080/add?a=100&b=200"; BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line = null; try { HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection(); con.setRequestMethod("GET"); // GET形式 br = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); sb.append("\r\n"); // ラインセパレータは決めうち } // 結果を出力 System.out.println(sb.toString()); } catch (IOException e) { e.printStackTrace(); // エラー処理 } finally { if (br != null) { br.close(); } } } public static void post() throws Exception { String url = "http://localhost:8080/add/add2"; BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line = null; try { HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection(); con.setRequestMethod("POST"); // POST形式 con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;"); PrintWriter pw = new PrintWriter(con.getOutputStream()); pw.print(URLEncoder.encode("a=12&b=13", "UTF-8")); pw.flush(); pw.close(); br = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); sb.append("\r\n"); // ラインセパレータは決めうち } // 結果を出力 System.out.println(sb.toString()); } catch (IOException e) { e.printStackTrace(); // エラー処理 } finally { if (br != null) { br.close(); } } } } |
Apache Commons の HttpClient ライブラリを使う場合
httpcomponents-client-4.5.1使用
httpcomponents-client-4.5.1-bin.zip(472)
1 |
package test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class TestClient3 { public static void main(String[] args) throws Exception { get(); post(); } public static void get() throws Exception { String url = "http://localhost:8080/add?a=100&b=200"; CloseableHttpClient client = null; CloseableHttpResponse response = null; BufferedReader br = null; try { client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); response = client.execute(httpGet); System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); System.out.println(entity); String line = null; StringBuilder sb = new StringBuilder(); br = new BufferedReader(new InputStreamReader(entity.getContent())); while ((line = br.readLine()) != null) { sb.append(line); sb.append("\r\n"); // ラインセパレータは決めうち } // 結果を出力 System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) br.close(); if (response != null) response.close(); if (client != null) client.close(); } } public static void post() throws Exception { String url = "http://localhost:8080/add/add2"; CloseableHttpClient client = null; CloseableHttpResponse response = null; BufferedReader br = null; try { client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> args = new ArrayList <NameValuePair>(); args.add(new BasicNameValuePair("a", "123")); args.add(new BasicNameValuePair("b", "456")); httpPost.setEntity(new UrlEncodedFormEntity(args)); response = client.execute(httpPost); System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); System.out.println(entity); String line = null; StringBuilder sb = new StringBuilder(); br = new BufferedReader(new InputStreamReader(entity.getContent())); while ((line = br.readLine()) != null) { sb.append(line); sb.append("\r\n"); // ラインセパレータは決めうち } // 結果を出力 System.out.println(sb.toString()); } catch (Exception e){ e.printStackTrace(); } finally { if (br != null) br.close(); if (response != null) response.close(); if (client != null) client.close(); } } } |
サーバ
Webサーバをプログラムで立てる場合
http://qiita.com/noobar/items/a96e07e441241b1e0215
http://unageanu.hatenablog.com/entry/20090723/1248353703
ライブラリを準備する
JAX-RSを実装するためのライブラリはいくつかあるが、ここではJerseyを使う。
ダウンロード
https://jax-rs-spec.java.net/
jersey以外にも JDK http server が必要。
jaxrs-ri-2.22.1.zip(444)
jersey-container-jdk-http-2.22.1.jar(338)
サービスクラスを書く
TestService.java
1 |
package test; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/test") public class TestService { @GET public String hello() { return "Hello World!"; } } |
Webサーバを起動するためのランチャを書く
Launcher.java
1 |
package test; import java.io.IOException; import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; import com.sun.net.httpserver.HttpServer; import java.net.*; import javax.ws.rs.core.UriBuilder; public class Launcher { public static void main ( String[] args ) throws IllegalArgumentException, IOException { URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build(); ResourceConfig config = new ResourceConfig(TestService.class); HttpServer server = JdkHttpServerFactory.createHttpServer(baseUri, config); } } |
Webサーバ実行確認
必要なクラスパスを通して
java test.Launcher
ブラウザで
http://localhost:8080/test
で
Hello World!
と出たらOK。
WebサーバをTomcatで行う場合
http://www.atmarkit.co.jp/ait/articles/1411/10/news105.html
tomcatの設定
tomcatを使えるようにしておく。
ディレクトリ構成
└─WEB-INF
│ web.xml │ ├─classes │ └─test │ TestService.class │ └─lib aopalliance-repackaged-2.4.0-b31.jar asm-debug-all-5.0.4.jar hk2-api-2.4.0-b31.jar hk2-locator-2.4.0-b31.jar hk2-utils-2.4.0-b31.jar javassist-3.18.1-GA.jar javax.annotation-api-1.2.jar javax.inject-2.4.0-b31.jar javax.servlet-api-3.0.1.jar javax.ws.rs-api-2.0.1.jar jaxb-api-2.2.7.jar jersey-client.jar jersey-common.jar jersey-container-servlet-core.jar jersey-container-servlet.jar jersey-guava-2.22.1.jar jersey-media-jaxb.jar jersey-server.jar org.osgi.core-4.2.0.jar osgi-resource-locator-1.0.1.jar persistence-api-1.0.jar validation-api-1.1.0.Final.jar
WEB-INF/lib にjarファイルをコピーする
WEB-INF/libにjerseyのapi、ext、libのjarをファイルをすべてコピーする。
サービスクラスを書く
1 |
package test; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; @Path("/test") @Produces(MediaType.TEXT_PLAIN) public class TestService { @GET public String hello() { return "Hello World!"; } public static void main(String[] args) { System.out.println(new TestService().hello()); } } |
引数をもらう書き方と複数のサービス書く書き方
下の例では、add2は
http://hostname/add
で、addメソッドを呼び
http://hostname/add/add2
でadd2メソッドを呼ぶ
1 |
package test; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.FormParam; @Path("/add") public class TestService2 { @GET public int add(@QueryParam("a") int a, @QueryParam("b") int b) { return a + b; } @POST @Path("/add2") public int add2(@FormParam("a") int a, @FormParam("b") int b) { return a + b; } } |
web.xmlを書く
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>JerseyRESTServer</display-name> <servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <!-- 自分で作成したパッケージを書く。複数ある場合は ; で区切る --> <param-value>test</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <!-- /* でもいいし、 /hoge/* でもよい --> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
実行確認
ブラウザで
http://localhost:8080/rest/test
URLのrestの部分はtomcatの設定次第。環境によって変わる。
[通知用URL]
Tweet
最終更新時間:2017年02月12日 22時02分30秒