我正在尝试将带有JSON数据的POST请求发送到某些Swagger API,但这会导致错误:
{"error":{"message":"Invalid json message received","status":400}}
代码如下:
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String date = "05/13/2019";
JSONObject jsonObject = new JSONObject();
jsonObject.put("startDate", date);
jsonObject.put("endDate", date);
HttpEntity<String> entity = new HttpEntity<>(jsonObject.toString(),headers);
String url = "https://api/reports/";
ResponseEntity<List> response = restTemplate.postForEntity(url,entity,List.class);
春季日志:
o.s.web.client.RestTemplate : HTTP POST https://api/reports/
o.s.web.client.RestTemplate : Accept=[application/json]
o.s.web.client.RestTemplate : Writing [{"endDate":"05/13/2019","startDate":"05/13/2019"}] as "application/json"
o.s.web.client.RestTemplate : Response 400 BAD_REQUEST
c.s.my.controller.ApiClient : Error.Body: {"error":{"message":"Invalid json message received","status":400}}
c.s.my.controller.ApiClient : Error.Headers: [Date:"Fri, 17 May 2019 07:18:03 GMT", Content-Type:"application/json", Transfer-Encoding:"chunked", Connection:"keep-alive", Server:"nginx", X-Powered-By:"PHP/5.6.32", Cache-Control:"no-cache"]
但是当我通过curl发送请求时:
curl -X POST "https://api/reports/" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"endDate\":\"05/13/2019\",\"startDate\":\"05/13/2019\"}"
一切正常!
当我尝试发送JSONObject时:
HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject,headers);
还有另一个错误:Response 422 UNPROCESSABLE_ENTITY
,响应正文:
{"errors":{"list":{"report_campaign_single_form":["This form should not contain extra fields.: empty"],"startDate":["This value should not be blank."],"endDate":["This value should not be blank."]},"status":422}}
我做错了什么?请帮忙。
答案 0 :(得分:0)
检查了CharlesProxy的请求后,我找到了答案!
当我以jsonObject
身份通过String
时:
HttpEntity<String> entity = new HttpEntity<>(jsonObject.toString(),headers);
请求看起来像:
"{\"endDate\":\"05/13/2019\",\"startDate\":\"05/13/2019\"}"
我们可以看到它不是正确的JSON数据,然后我将jsonObject
作为Map
传递:
HttpEntity<Map> entity = new HttpEntity<>(jsonObject.toMap(),headers);
它运行完美:
{
"endDate": "05/13/2019",
"startDate": "05/13/2019"
}
给我200 OK响应