Spring RestTemplate,在解析为Json之前拦截响应 [英] Spring RestTemplate, intercepting response before parsing to Json
问题描述
我有一个REST api,它在主体内容中响应了一些其他非JSON数据.这中断了RestTemplate和jackson的使用.我可以在解析之前拦截http响应正文吗?
I have a REST api that responds with some additional non JSON data in the body content. This breaks the use of RestTemplate and jackson. Can I intercept the http response body prior to the parsing?
我正在使用RestTemplate.getForObject.
I am using RestTemplate.getForObject.
我看过RestTemplate,找不到合适的方法.
I've taken a look at the RestTemplate and couldn't see an appropriate method.
推荐答案
You can try to implement ClientHttpRequestInterceptor
and assign it to restTemplate
. Implement intercept
method:
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes,
ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
ClientHttpResponse response=clientHttpRequestExecution.execute(httpRequest, bytes);
//...do magic with response body from getBody method
return response;
}
您可能需要使用自己的实现扩展AbstractClientHttpResponse
来实现.
You might have to extend AbstractClientHttpResponse
with your own implementation to do that.
另一种选择是将来自REST API的响应视为字符串,然后根据需要设置字符串格式,并使用ObjectMapper明确将其映射到对象.
Another option could be to treat the response from the REST API as String, then format the string as needed and explicitly map it to object using ObjectMapper.
然后在您的restTemplate
中,您将拥有:
Then in your restTemplate
you would have:
String result = restTemplate.getForObject(url, String.class, host);
//..trim the extra stuff
MyClass object=objectMapper.readValue(result, MyClass.class);
另一个选择是实现自己的HttpMessageConverter
,该HttpMessageConverter
扩展了AbstractJackson2HttpMessageConverter
并将其注册到restTemplate
.我认为从春季的角度来看这将是最清洁的生活
Yet another option would be to implement your own HttpMessageConverter
which extends AbstractJackson2HttpMessageConverter
and register it with restTemplate
. In my opinion that would be the cleaneast from the Spring point of view
这篇关于Spring RestTemplate,在解析为Json之前拦截响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!