2014-10-30 58 views
3

以下是我對服務器:如何通過澤西發送和接收包含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。

回答

1

由於Jersey資源和客戶端請求不匹配,您將收到406錯誤:Jersey正在生成文本響應,但您的客戶端聲明它只接受JSON。下面是W3C說,大約一個406錯誤:

The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

你需要更改你的球衣PUT方法產生JSON ...

... 
@Produces({ MediaType.APPLICATION_JSON }) 
public Response insertMessage(Message m) { 
    return Response.ok(m.toString()).build(); 
} 

或者使用text/plain有關您接受媒體類型客戶端請求:

service.accept(MediaType.TEXT_PLAIN); 

尋找你的修改,原來的415錯誤是由客戶端請求中缺少service.type(MediaType.APPLICATION_JSON)引起的。再從W3C,一個415錯誤是:

The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.

這裏是W3C參考我使用的是:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

+0

是否真的'返回Response.ok(m.toString(),TYPE).build();'和'TYPE'在'service.accept(TYPE)應該是一樣的嗎? – wwood 2014-11-04 14:28:20

+0

是的。你應該簡化你的'insertMessage'方法並推遲到'@ Produces'註釋。我已經更新了我的答案。 – sherb 2014-11-04 16:27:04

+0

非常感謝 – wwood 2014-11-04 16:45:25

0

你的HTTP響應代碼爲

415 Unsupported Media Type 

你嘗試設置WebResource在接受財產? 事情是這樣的:

service.accept(MediaType.APPLICATION_JSON); 

就拿這個topic看看。似乎是同樣的問題。

+0

我已經更新的問題,它的406現在...... – wwood 2014-11-04 04:46:27

+1

我已經解決這個問題了,謝謝非常! – wwood 2014-11-04 20:32:39

+0

你做了什麼來解決? – dansouza 2014-11-14 13:34:49