【发布时间】:2012-01-04 17:48:35
【问题描述】:
是否可以使用 POST 将包装对象传递给 REST Web 服务?
【问题讨论】:
-
我不确定您对 wrapper object 的含义,但服务器必须知道该包装器对象。您不能只创建一个对象并将其发送到服务器,因为它不知道如何反序列化它。
-
我觉得这个问题可以帮到你:stackoverflow.com/questions/1071749/…
是否可以使用 POST 将包装对象传递给 REST Web 服务?
【问题讨论】:
是的,您可以传递一个 Wrapper Oject(一个类的对象)。
jersey Rest 客户端示例:
添加依赖:
<!-- jersey -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
ForGetMethod 并传递两个参数:
Client client = Client.create();
WebResource webResource1 = client
.resource("http://localhost:10102/NewsTickerServices/AddGroup/"
+ userN + "/" + groupName);
ClientResponse response1 = webResource1.get(ClientResponse.class);
System.out.println("responser is" + response1);
GetMethod 传递一个参数并获取 List 的响应:
Client client = Client.create();
WebResource webResource1 = client
.resource("http://localhost:10102/NewsTickerServices/GetAssignedUser/"+grpName);
//value changed
String response1 = webResource1.type(MediaType.APPLICATION_JSON).get(String.class);
List <String > Assignedlist =new ArrayList<String>();
JSONArray jsonArr2 =new JSONArray(response1);
for (int i =0;i<jsonArr2.length();i++){
Assignedlist.add(jsonArr2.getString(i));
}
In Above It 返回一个 List ,我们将其作为 List 接受,然后将其转换为 Json Array ,然后将 Json Array 转换为 List 。
如果 Post Request 传递 Json 对象作为参数:
Client client = Client.create();
WebResource webResource = client
.resource("http://localhost:10102/NewsTickerServices/CreateJUser");
// value added
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class,mapper.writeValueAsString(user));
if (response.getStatus() == 500) {
context.addMessage(null, new FacesMessage("User already exist "));
}
这里 User 是用户类的对象。其中 m pssing 在 post 参数中。
【讨论】: