如何使用球衣发送和接收包含 JSON 的 PUT 请求?

2024-02-13

这是我的服务器:

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


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

请求所标识的资源仅能够生成根据请求中发送的接受标头具有不可接受的内容特征的响应实体。

您需要更改 Jersey PUT 方法来生成 JSON...

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

Or use 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 http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用球衣发送和接收包含 JSON 的 PUT 请求? 的相关文章

随机推荐