【发布时间】:2019-05-17 07:57:30
【问题描述】:
我正在尝试将带有 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}}
我做错了什么?请帮忙。
【问题讨论】:
-
你的 swagger api 收到了什么?
-
@AmerQarabsa 我不知道,因为它是远程 API
-
你不知道你调用的 api 需要什么?你应该可以通过swagger看到这一点
-
@AmerQarabsa API 只需要 2 个字符串参数:startDate 和 endDate prntscr.com/nppk21
标签: java json spring post resttemplate