【问题标题】:About how to send and receive a PUT request with Jersey关于如何使用 Jersey 发送和接收 PUT 请求
【发布时间】:2014-10-31 15:46:56
【问题描述】:

我按照中的答案

Post/Put/Delete http Json with additional parameters in Jersey + general design issues

但我继续收到400 Bad Request...知道如何解决这个问题吗?

这是我为 jersey restful server 准备的:

@PUT
@Path("/insertmessage")
@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"));
System.out.print(service.path("insertmessage")
       .type(MediaType.APPLICATION_JSON).put(String.class, json));

这是消息的构造函数:

@JsonCreator
public Message(@JsonProperty("sender") String sender,
               @JsonProperty("receiver") String receiver,
               @JsonProperty("content") String content) {
    this.sender = sender;
    this.receiver = receiver;
    this.content = content;
}

我有:

<init-param>
     <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
     <param-value>true</param-value>
</init-param>

在我的 web.xml 中

【问题讨论】:

    标签: java json rest jersey


    【解决方案1】:

    如果您使用 Jersey 2.x,您可以使用代理客户端,这样您就可以像调用本地类一样调用服务。
    至于您的代码,不清楚什么是控制器注释和路径。我说的是这部分path("rest")

    【讨论】:

    • 我的道歉,这是一个错字...我使用的是 Jersey 1.18。我的问题是如何将对象发送到服务器以及服务器如何接收此对象。目前我正在使用 Jackson 序列化对象,但它一直显示 400 错误
    • 如果您设置了 POJO_MAPPING,则无需显式映射对象。你甚至不需要注释 Message 类。考虑到 getBaseURI() 返回正确的值,它应该可以工作。使用 curl 或其他手控客户端检查您的服务器。 400 表示您在 http 请求本身而不是在 json 中有错误。我推荐 Jersey 2.x,因为 1.x 很乱。您将不需要所有这些错误的字符串文字、响应构建等。
    • “你不需要显式映射对象”是指我不需要使用Jackson显式序列化对象而是直接发送对象本身?
    • 是的,您只需将对象传递给 put()。 Jersey 应自行将其转换为适当的 mime 类型。如果我的想法没有让我失望;)
    • 谢谢,有时间我试试。
    猜你喜欢
    • 2014-12-25
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 2015-07-25
    • 2011-07-20
    • 1970-01-01
    相关资源
    最近更新 更多