[英]Rest API sends response as plain string however Content Type is "application/json;charset=UTF-8". How can I readthe response
We are consuming a third party rest API that returns a UUID as a response to a POST request.我们正在使用第三方 rest API,它返回一个 UUID 作为对 POST 请求的响应。 The MediaType of the response is
application/json
, however the returned uuid is returned as plain text and not as a JSON like "7c49cec7-8ae8-44c8-bc27-866b6efcfe59"
(with quotes).响应的 MediaType 是
application/json
,但是返回的 uuid 以纯文本形式返回,而不是像"7c49cec7-8ae8-44c8-bc27-866b6efcfe59"
(带引号)那样的 JSON。 I have attached MappingJackson2HttpMessageConverter to the Spring RestTemplate.我已将 MappingJackson2HttpMessageConverter 附加到 Spring RestTemplate。 It appears(I'm not sure) that since content type is
application/json
it tries to parse it as JSON and fails to parse it because it doesn't contain double quotes.看起来(我不确定)因为内容类型是
application/json
它试图将它解析为 JSON 并且无法解析它,因为它不包含双引号。 Following is the exception以下是例外
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]
Code:代码:
@Test
public void test1() {
String uuid = restTemplate.postForObject("/order", orderDTO, String.class);
assertThat(uuid).isNotNull();
}
How can I deal with this situation?我该如何处理这种情况?
I tried the following solution.我尝试了以下解决方案。 It works, but it also forces the conversion of all other media type
application/json
responses to be handled by StringHttpMessageConverter
instead of MappingJackson2HttpMessageConverter
.它有效,但它也强制所有其他媒体类型
application/json
响应的转换由StringHttpMessageConverter
而不是MappingJackson2HttpMessageConverter
处理。 I added an interceptor which intercepts the reponse before converting it and then modifies the content type.我添加了一个拦截器,它在转换之前拦截响应,然后修改内容类型。
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.