我正在创建一个Web应用程序。我想使用Java SE应用程序执行管理操作。为此,我在SE项目中创建了一个RESTful ShoppingAdminClient
。我需要从客户端将JSON对象传递给服务器。我试过这个,
public static void main(String[] args) throws JSONException {
ShoppingAdminClient sac = new ShoppingAdminClient();
JSONObject jo = new JSONObject();
jo.put("itemName", "Itemms");
sac.create_JSON(jo);
}
但我得到以下例外,
Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class shoppingadmin.Item, and MIME media type, application/json, was not found
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
at com.sun.jersey.api.client.Client.handle(Client.java:648)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:563)
at shoppingadmin.ShoppingAdminClient.create_JSON(ShoppingAdminClient.java:69)
at shoppingadmin.ShoppingAdmin.main(ShoppingAdmin.java:27)
Caused by: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class shoppingadmin.Item, and MIME media type, application/json, was not found
at com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:288)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:204)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:147)
... 6 more
Java Result: 1
如何将JSON类型对象传递给服务器?
提前致谢!
答案 0 :(得分:3)
对于Jersey客户端,您可以创建Jersey Client实例以将JSON发布到服务器。因此,为了发送JSON格式,您可以使用Jackson JSON library并通过添加Jersey-JSON jar将其与Jersey捆绑在一起。您还需要添加Jersey客户端依赖项。
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.17</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.17</version>
</dependency>
然后您的客户端代码将如下所示:
public String requestResource(String baseURL, String path) {
Client wsClient = Client.create();
WebResource rs = wsClient.resource(baseURL);
String response = rs.path(path).type(MediaType.APPLICATION_JSON).post(String.class, item);
return response;
}
请注意MediaType.APPLICATION_JSON
方法中的type
指定数据格式。这里item
包含您要发送到服务器的数据。另外,不要忘记在web.xml
中添加以下行,以便所有POJO类自动序列化为JSON。
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>