java - 通过 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}}
我做错了什么?请帮忙。
解决方案
在使用 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 响应
推荐阅读
- javascript - IndexedDB 和游标
- gitlab - Gitlab CI 使用导出变量
- java - 关闭飞行模式后,为什么 Android 应用程序会通过 Activity 和 Fragment 生命周期方法
- sql - 清理不再被任何子引用的父表行
- python - 删除 Python 列表中特定的相同后续值
- c++ - 如何模拟在 C++ 中按住键盘键
- javascript - 滚动超出文档中的特定点后激活动画
- c - C 宏的参数受参数前缀限制
- c++ - 当 std::array 是模板化函数/通用 lambda 的输入时,为什么它不是常量表达式?
- javascript - 使用延迟加载不会显示图像