【Java】【REST】JavaでRESTRestクライアント を実装する ~ライブラリ jersey-client を使用した場合 ~

設定

 [1] 以下のサイトから、jarファイル「jersey-bundle-1.17.1.jar」を入手する
https://jersey.java.net/download.html
 [2] 上記のJarをインポートする

 (例えば、Eclipseの場合、プロジェクトを右クリックし、
  [Propaties]-[Java Build Paht]-[Libraries]-[Add External JARs]で
  上記のJARファイルを追加する)

サンプル

例1

使用するWebサービス

http://weather.livedoor.com/weather_hacks/webservice
に乗っている以下のサービス。
http://weather.livedoor.com/forecast/webservice/json/v1?city=400040

SamleRestWithJerseyClient.java

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;


public class SamleRestWithJerseyClient {   
   public static void main(String args[]) throws Exception {
      Client client = Client.create();
        WebResource webResource =
      client.resource("http://weather.livedoor.com/forecast/webservice/json/v1?city=400040");
        String json = webResource.accept("application/json").get(String.class);
        System.out.println(json);
   }
}

出力

{"pinpointLocations":[{"link":"http://weather.livedoor.com/area/forecast/4020200","name":"\u5927\u725f\u7530\u5e02"}, ..."publicTime":"2013-12-29T16:42:00\u002b0900"}}

例2

使用するWebサービス

 * Axis2で自作したサービス(例えば、以下のURLを参考)を起動させて、実行した
http://blogs.yahoo.co.jp/dk521123/31944955.html

SamleRestWithJerseyClient.java

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

public class SamleRestWithJerseyClient {
	public static void main(String args[]) throws Exception {
		Client client = Client.create();
		WebResource webResource = 
				client.resource("http://localhost:8080/Axis2Sample/services/HelloWorld/SayHello?name=Mike");
		String xml = webResource.accept("application/xml").get(String.class);
		System.out.println(xml);
	}
}

出力

<ns:SayHelloResponse xmlns:ns="Hello">http://services.demo">Hello Mike</ns:return></ns:SayHelloResponse>


関連記事

JavaでRESTRestクライアント を実装する

Axis2 を使用した場合

http://blogs.yahoo.co.jp/dk521123/32790425.html

ライブラリ jersey-client を使用した場合

http://blogs.yahoo.co.jp/dk521123/32824085.html

HttpURLConnection を使用した場合

http://blogs.yahoo.co.jp/dk521123/32936064.html

Apache Commons を使用した場合

http://blogs.yahoo.co.jp/dk521123/32936814.html