[英]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.