首页 > 解决方案 > 通过 RestTemplate POST JSON 对象导致响应 400 BAD_REQUEST

问题描述

我正在尝试将带有 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}}

我做错了什么?请帮忙。

标签: javajsonspringpostresttemplate

解决方案


在使用 CharlesProxy 检查请求后,我找到了答案!

当我jsonObject作为String

HttpEntity<String> entity = new HttpEntity<>(jsonObject.toString(),headers);

请求看起来像:

"{\"endDate\":\"05/13/2019\",\"startDate\":\"05/13/2019\"}"

我们可以看到它不是正确的 JSON 数据,然后我传递jsonObjectMap

HttpEntity<Map> entity = new HttpEntity<>(jsonObject.toMap(),headers);

它完美无缺:

{
    "endDate": "05/13/2019",
    "startDate": "05/13/2019"
}

给我带来 200 OK 响应


推荐阅读