我们正在使用第三方rest,它返回一个UUID作为对POST请求的响应。响应的MediaType是application/json
,但是返回的uuid作为纯文本返回,而不是作为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();
}
我该如何处理这种情况?
发布于 2020-09-18 22:12:22
我尝试了下面的解决方案。它可以工作,但它也强制所有其他媒体类型的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;
});
https://stackoverflow.com/questions/63963180
复制相似问题