以下是我對服務器:如何通過澤西發送和接收包含JSON的PUT請求?
@PUT
@Path("/put")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.TEXT_PLAIN })
public Response insertMessage(Message m) {
return Response.ok(m.toString(), MediaType.TEXT_PLAIN).build();
}
客戶端:
ClientConfig config = new DefaultClientConfig();
config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(new Message("a", "b", "message"));
ClientResponse response = service.path("put").accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON)
.put(ClientResponse.class, json);
System.out.println(response.getStatus() + " " + response.getEntity(String.class));
對於消息:
public class Message {
private String sender;
private String receiver;
private String content;
@JsonCreator
public Message() {}
@JsonCreator
public Message(@JsonProperty("sender") String sender,
@JsonProperty("receiver")String receiver,
@JsonProperty("content")String content) {
this.sender = sender;
this.receiver = receiver;
this.content = content;
}
}
而且我一直得到HTTP 406我有
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
in我的web.xml。
是否真的'返回Response.ok(m.toString(),TYPE).build();'和'TYPE'在'service.accept(TYPE)應該是一樣的嗎? – wwood 2014-11-04 14:28:20
是的。你應該簡化你的'insertMessage'方法並推遲到'@ Produces'註釋。我已經更新了我的答案。 – sherb 2014-11-04 16:27:04
非常感謝 – wwood 2014-11-04 16:45:25