【问题标题】:How to send and receive a PUT request containing JSON with jersey?如何使用球衣发送和接收包含 JSON 的 PUT 请求?
【发布时间】:2014-12-25 23:54:03
【问题描述】:

这是我的服务器:

@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>

在我的 web.xml 中。

【问题讨论】:

    标签: java json jersey put


    【解决方案1】:

    你得到的HTTP响应码是

    415 Unsupported Media Type
    

    您是否尝试在 WebResource 上设置接受属性? 像这样的:

    service.accept(MediaType.APPLICATION_JSON);
    

    看看这个topic。似乎是同样的问题。

    【讨论】:

    • 添加 service.accept(MediaType.APPLICATION_JSON);部分(服务器端)所以我收到错误 406,然后我添加 service.accept(MediaType.TEXT_PLAIN);给客户,现在一切都很好
    【解决方案2】:

    您收到 406 错误,因为您的 Jersey 资源和您的客户端请求不匹配:Jersey 正在生成文本响应,但您的客户端声明它只会接受 JSON。以下是 W3C 关于 406 错误的说明:

    请求标识的资源只能生成响应实体,其内容特征根据请求中发送的accept headers是不可接受的。

    您需要更改 Jersey 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 错误是:

    服务器拒绝为请求提供服务,因为请求实体的格式不受所请求方法的请求资源支持。

    这是我正在使用的 W3C 参考:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

    【讨论】:

    • return Response.ok(m.toString(), TYPE).build();中的TYPEservice.accept(TYPE)中的TYPE是否应该相同?
    • 是的。您应该简化您的 insertMessage 方法并遵循 @Produces 注释。我已经更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2019-12-12
    相关资源
    最近更新 更多