我有这个代码

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    client.addFilter(new HTTPBasicAuthFilter(adminUser, adminPass));
    client.addFilter(new LoggingFilter(System.out));

    WebResource service = client.resource(baseURL);
    ClientResponse clientResponse = service.path("api")
            .path("v1")
            .path("shoppers")
            .path(orderId)
            .path("status.json").accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, request);


每当我尝试发布类似的JSON请求时,我都会收到HTTP 415错误响应。对此问题进行一点挖掘后发现,JERSEY没有正确地整理我的对象。通过添加LoggingFilter,我可以看到在请求正文中,JAXBObject已损坏到XML,而不是JSON

这是JERSEY的已知行为吗?我在这里该怎么办?

最佳答案

您可能需要在请求时调用type()来设置内容类型(我假设Jersey对此做了一些聪明的事情):

.path("status.json")
.type(MediaType.APPLICATION_JSON) // <-- This line
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, request);


Other resources表示您可能需要使用ObjectMapper手动执行此操作:

ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(jsonObj);

10-07 13:23
查看更多