Jersey客户端API调用REST风格的Web服务
来源:互联网 发布:收银软件开发 编辑:程序博客网 时间:2024/05/16 11:39
Jersey 客户端 API 基础
jersey-1.14.jar 密码: cxug
要开始使用 Jersey 客户端 API,你首先需要创建一个 com.sun.jersey .api.client.Client 类的实例。下面是最简单的方法:
import com.sun.jersey .api.client.Client;Client client = Client.create();
Client 类是创建一个 RESTful Web Service 客户端的主要配置点。你可以使用它来配置不同的客户端属性和功能,并且指出使用哪个资源提供者。创建一个 Client 类的实例是一个比较昂贵的操作,所以尽量避免创建一些不需要的客户端实例。比较好的方式是尽可能地复用已经存在的实例。
当你创建完一个 Client 类的实例后,你可以开始使用它。无论如何,在发出请求前,你需要创建一个 Web Resource 对象来封装客户端所需要的 Web 资源。
Web 资源创建了一个 WebResponse 对象:
import
com.sun.jersey .api.client.WebResource;
Web Resource webResource = c.resource(
"http://example.com/base"
);
通过使用 WebResource 对象来创建要发送到 Web 资源的请求,以及处理从 Web 资源返回的响应。例如,你可以使用 WebResource 对象来发送 HTTP GET、PUT、POST 以及 DELETE 请求。
GET 请求:使用 WebResource 类的 get() 方法来提交一个 HTTP GET请求到 Web 资源:
String s = webResource.get(String.class);
这表示如果 WebResource 对象的 URL 是 http://example.com/base,那么一个 HTTP GET 请求将会发送到地址为 http://example.com/base 的资源。
String s = webResource.get(String.class);
你还可以指定 get() 请求时的查询参数。例如,下面的代码在 get() 请求中指定了两个查询参数:
MultivaluedMap queryParams =
new
MultivaluedMapImpl();
queryParams.add(
"param1"
,
"val1"
);
queryParams.add(
"param2"
,
"val2"
);
String s = webResouce.queryParams(queryParams).get(String.
class
);
你还可以指定响应所能接受的 MIME 类型。例如,下面的代码指定了响应的 MIME 类型只能为文本:
String s = webResource.accept("text/plain").get(String.class);
你还可以获取对应请求的 HTTP 状态码,例如下面这个例子展示获取一个请求所返回的文本实体与状态码:
ClientResponse response = webResource.accept(
"text/plain"
)
.get(ClientResponse.
class
);
int
status = response.getStatus();
String textEntity = response.getEntity(String.
class
);
ClientResponse 对象代表了一个客户端收到的 HTTP 响应。
PUT 请求 :使用 WebResource 类的 put() 方法来提交一个 HTTP PUT 请求到 Web 资源。例如下面的代码展示了请求发送一个文本实体 foo:bar 到指定的 Web 资源:
ClientResponse response = webResource.type(
"text/plain"
)
.put(ClientResponse.
class
,
"foo:bar"
);
同样,你也可以在使用 put() 方法发送请求时指定查询参数,方法与使用 get() 方法时指定查询参数一样。在下面的例子中,把在之前 get() 方法示例中使用过的两个同样的查询参数指定到了一个 put() 请求中:
MultivaluedMap queryParams =
new
MultivaluedMapImpl();
queryParams.add(
"param1"
,
"val1"
);
queryParams.add(
"param2"
,
"val2"
);
ClientResponse response = webResource.queryParams(queryParams)
.put(ClientResponse.
class
,
"foo:bar"
);
POST 请求 :一个 POST 请求相当于一个 GET 请求和一个 PUT 请求的综合,也就意味着,你可以使用 POST 请求来发送一个实体到指定的 Web 资源并且接收另一个实体。使用 WebResource 类的 post() 方法来发送一个 HTTP POST 请求到指定的 Web 资源。下面的例子展示了发送一个带有查询参数以及进行了 URL 编码的表单数据的 POST 请求:
MultivaluedMap formData =
new
MultivaluedMapImpl();
formData.add(
"name1"
,
"val1"
);
formData.add(
"name2"
,
"val2"
);
ClientResponse response = webResource.type(
"application/x-www-form-urlencoded"
)
.post(ClientResponse.
class
, formData);
DELETE 请求:使用 Web Resource 类的 delete() 方法来发送珍上 HTTP DELETE 请求到指定的 Web 资源。例如,下面的例子展示删除一个 URI 为 http://example.com/base/user/123 资源:
ClientResponse response = webResource.path(
"user/123"
)
.delete(ClientResponse.
class
);
另外,Web Resource.path() 方法可以在所有 HTTP 请求中使用,它可以让你给要请求的 Web 资源指定一个额外的路径。另一个 WebResouce 类的方法 header() 可以给你的请求添加 HTTP 头部信息。
另外如果表单提交的话,需要new Form来作为参数提交。
一个基于 Jersey 客户端的示例
1 import com.alibaba.fastjson.JSON; 2 import com.alibaba.fastjson.JSONArray; 3 import com.alibaba.fastjson.JSONObject; 4 import com.rimi.medical.common.domain.ResultPojo; 5 import com.sun.jersey.api.client.Client; 6 import com.sun.jersey.api.client.ClientResponse; 7 import com.sun.jersey.api.client.WebResource; 8 import com.sun.jersey.core.util.MultivaluedMapImpl; 9 10 import javax.ws.rs.core.MediaType; 11 import javax.ws.rs.core.MultivaluedMap; 12 import java.util.ArrayList; 13 import java.util.Iterator; 14 import java.util.List; 15 import java.util.Map; 16 17 /** 18 * JerseyAPi客户端 19 * Created by libt on 2015/01/30. 20 */ 21 public class JerseyClientUtil { 22 23 private static final String BIGDATA_API_URL = ReadSettingProperties.getValue("bigdata_api_url"); 24 25 /** 26 * post方法 27 * 28 * @param method 方法名 29 * @param param 参数 30 * @return 返回值 31 */ 32 public static ResultPojo postMethod(String method, String param) { 33 ResultPojo resultPojo = new ResultPojo(); 34 ClientResponse response = null; 35 try { 36 Client client = Client.create(); 37 WebResource resource = client.resource(BIGDATA_API_URL + method); 38 response = resource.type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, param); 39 int status = response.getStatus(); 40 String data = response.getEntity(String.class); 41 if (status == 200) { 42 JSONObject jsonObject = JSON.parseObject(data); 43 resultPojo.setStatus(jsonObject.getInteger("status")); 44 resultPojo.setData(data); 45 } else { 46 resultPojo.setStatus(response.getStatus()); 47 resultPojo.setData(data); 48 } 49 } catch (Exception e) { 50 resultPojo.setStatus(500);//服务器异常 51 resultPojo.setErrorMsg(e.getMessage()); 52 } finally { 53 if (response != null) { 54 response.close(); 55 } 56 } 57 return resultPojo; 58 } 59 60 61 /** 62 * get方法 63 * 例如:consultation/recommend?startDate=201412030253&endDate=201412020253 64 * @param method 方法名 65 * @param param 参数 66 * @return 返回值 67 */ 68 public static ResultPojo getMethod(String method, String param) { 69 ResultPojo resultPojo = new ResultPojo(); 70 ClientResponse response = null; 71 try { 72 Client client = Client.create(); 73 WebResource resource = client.resource(BIGDATA_API_URL + method); 74 response = resource.queryParams(parseJSON2Map(param)).accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class); 75 int status = response.getStatus(); 76 String data = response.getEntity(String.class); 77 if (status == 200) { 78 JSONObject jsonObject = JSON.parseObject(data); 79 resultPojo.setStatus(jsonObject.getInteger("status")); 80 resultPojo.setData(data); 81 } else { 82 resultPojo.setStatus(response.getStatus()); 83 resultPojo.setData(response.getEntity(String.class)); 84 } 85 } catch (Exception e) { 86 e.printStackTrace(); 87 resultPojo.setStatus(500);//服务器异常 88 resultPojo.setErrorMsg(e.getMessage()); 89 } finally { 90 if (response != null) { 91 response.close(); 92 } 93 } 94 return resultPojo; 95 } 96 97 /** 98 * get方法 99 * 例如:consultation/recommend/A1000037B04B8C100 * @param method 方法名101 * @param param 参数102 * @return 返回值103 */104 public static ResultPojo getMethodOnly(String method, String param) {105 ResultPojo resultPojo = new ResultPojo();106 ClientResponse response = null;107 try {108 Client client = Client.create();109 WebResource resource = client.resource(BIGDATA_API_URL + method + param);110 response = resource.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);111 int status = response.getStatus();112 String data = response.getEntity(String.class);113 if (status == 200) {114 JSONObject jsonObject = JSON.parseObject(data);115 resultPojo.setStatus(jsonObject.getInteger("status"));116 resultPojo.setData(data);117 } else {118 resultPojo.setStatus(response.getStatus());119 resultPojo.setData(response.getEntity(String.class));120 }121 } catch (Exception e) {122 e.printStackTrace();123 resultPojo.setStatus(500);//服务器异常124 resultPojo.setErrorMsg(e.getMessage());125 } finally {126 if (response != null) {127 response.close();128 }129 }130 return resultPojo;131 }132 133 public static MultivaluedMap parseJSON2Map(String jsonStr) {134 MultivaluedMap queryParams = new MultivaluedMapImpl();135 //最外层解析136 JSONObject json = JSON.parseObject(jsonStr);137 for (Map.Entry<String, Object> entry : json.entrySet()) {138 Object v = entry.getValue();139 //如果内层还是数组的话,继续解析140 if (v instanceof JSONArray) {141 List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();142 Iterator<Object> it = ((JSONArray) v).iterator();143 while (it.hasNext()) {144 JSONObject json2 = (JSONObject) it.next();145 list.add(parseJSON2Map(json2.toJSONString()));146 }147 queryParams.add(entry.getKey(), list);148 } else {149 queryParams.add(entry.getKey(), v);150 }151 }167 return queryParams;168 }169 170 171 public static void main(String[] args) {172 173 // ResultPojo resultPojo = postMethod("bfr/bfr_choices", "{\"userid\":\"00004\",\"createTime\":\"2014-09-23 16:19:23\",\"bmiScore\":\"80\",\"imageNum\":\"01\",\"type\":\"0\",\" info \":\"个人身体质量分析正常\"}");174 ResultPojo resultPojo = getMethod("recommendInfo/query", "{\"endDate\":\"201412020253\",\"startDate\":\"201410010253\"}");175 // ResultPojo resultPojo = getMethodOnly("consultation/recommend/", "A1000037B04B8C");176 System.out.println(resultPojo.getStatus());177 System.out.println(resultPojo.getErrorMsg());178 179 }180 }
- 通过 Jersey 客户端 API 调用 REST 风格的 Web 服务
- 通过 Jersey 客户端 API 调用 REST 风格的 Web 服务
- 通过Jersey客户端API调用REST风格的Web服务
- 通过 Jersey 客户端 API 调用 REST 风格的 Web 服务
- 通过 Jersey 客户端 API 调用 REST 风格的 Web 服务
- 通过 Jersey 客户端 API 调用 REST 风格的 Web 服务
- Jersey客户端API调用REST风格的Web服务
- 通过Jersey客户端API调用REST风格的Web服务
- 通过Jersey客户端API调用RestFul风格的Web服务
- 通过Jersey客户端API调用RestFul风格的Web服务
- Jersey构建RESTful服务4--通过jersey-client客户端调用Jersey的Web服务模拟CURD
- jersey 搭建rest风格服务
- java调用rest风格web服务的两种方式
- java调用rest风格web服务的两种方式
- REST及REST风格的Web服务
- 用Jersey构建RESTful服务4--通过jersey-client客户端调用Jersey的Web服务模拟CURD
- 用Jersey构建RESTful服务4--通过jersey-client客户端调用Jersey的Web服务模拟CURD
- 用Jersey构建RESTful服务4--通过jersey-client客户端调用Jersey的Web服务模拟CURD
- 图像滤镜艺术----Brannan滤镜
- KVO的基本使用
- linux关闭启动防火墙
- 使用MVC模型的用户登录及注册(注销部分)
- Fresco简单使用
- Jersey客户端API调用REST风格的Web服务
- 【Codeforces 713B&714D】 Searching Rectangles【贪心】
- turtlebot入门仿真
- NOI2014购票
- Docker Engine还有比这更棒的东西了吗?
- Java基础:String类
- SpringMVC页面向Controller提交数组+Mybatis传多个参数+MySQL一次写入多条记录
- 背包问题之一(回溯法)
- Android 中的Handler机制