繁体   English   中英

通过Jersey发布JSON

[英]Posting JSON via Jersey

我有这个代码

    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);

其他资源表明您可能需要使用ObjectMapper手动执行此操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM