![](/img/trans.png)
[英]The content type application/json; charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)
[英]Rest API sends response as plain string however Content Type is "application/json;charset=UTF-8". How can I readthe response
我们正在使用第三方 rest API,它返回一个 UUID 作为对 POST 请求的响应。 响应的 MediaType 是application/json
,但是返回的 uuid 以纯文本形式返回,而不是像"7c49cec7-8ae8-44c8-bc27-866b6efcfe59"
(带引号)那样的 JSON。 我已将 MappingJackson2HttpMessageConverter 附加到 Spring RestTemplate。 看起来(我不确定)因为内容类型是application/json
它试图将它解析为 JSON 并且无法解析它,因为它不包含双引号。 以下是例外
org.springframework.web.client.RestClientException: Error while extracting response for type [class java.lang.Object] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('d' (code 100)): Expected space separating root-level values; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('d' (code 100)): Expected space separating root-level values
at [Source: (PushbackInputStream); line: 1, column: 3]
代码:
@Test
public void test1() {
String uuid = restTemplate.postForObject("/order", orderDTO, String.class);
assertThat(uuid).isNotNull();
}
我该如何处理这种情况?
我尝试了以下解决方案。 它有效,但它也强制所有其他媒体类型application/json
响应的转换由StringHttpMessageConverter
而不是MappingJackson2HttpMessageConverter
处理。 我添加了一个拦截器,它在转换之前拦截响应,然后修改内容类型。
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(List.of(MediaType.APPLICATION_JSON));
messageConverters.add(converter);
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setSupportedMediaTypes(List.of(MediaType.TEXT_PLAIN));
messageConverters.add(stringHttpMessageConverter);
restTemplate
.getInterceptors()
.add(
(request, body, execution) -> {
ClientHttpResponse response = execution.execute(request, body);
response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
return response;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.