RestTemplate convertor stopped working by adding interceptor

六眼飞鱼酱① 提交于 2021-02-11 15:01:34

问题


I have a spring boot 2 application, in which I have to log every request and response made by using Rest Template. For instance, if I have to call another service, this needs to get logged in my db. For this, I made the following changes in the Rest Template Config

@Configuration
@Getter
public class RestTemplateConfig {

@Bean
public RestTemplate restTemplate() {
    RestTemplate template = new RestTemplate();

    List<ClientHttpRequestInterceptor> interceptors = template.getInterceptors();
    if (CollectionUtils.isEmpty(interceptors))
        interceptors = new ArrayList<>();

    interceptors.add(new RequestResponseLoggingInterceptor());
    template.setInterceptors(interceptors);
    return template;
}
}

And the interceptor code is

public class RequestResponseLoggingInterceptor implements ClientHttpRequestInterceptor {

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {

    ResponseLoggingRepository loggingRepository = BeanUtils.getBean(ResponseLoggingRepository.class);
    ResponseLoggingEntity entity = ResponseLoggingEntity.build(request, body);
    loggingRepository.save(entity);
    ClientHttpResponse response = execution.execute(request, body);
    ResponseLoggingEntity.build(response, entity);
    loggingRepository.save(entity);
    return response;
}

}

The code works perfectly fine and I'm successfully able to log the response in the db. The issue is when I use the rest template exchange method, I always receive the null object.

ResponseObject response = restTemplate.postForObject(url, requestObject,
                ResponseObject.class);

This response object is always null whenever I test. However, if I remove the interceptor from the rest template, I get proper response in my object.

I further debugged and checked for the internal converters at the time of rest template config initialization, and I'm able to see the MappingJackson2HttpMessageConverter which as per my understanding, is the one which converts the response from JSON to the required object. I think some additional configuration is needed so that the response object obtains the required mapping and I have no clue as to what is missing in this case? Could anyone please help? Thanks.

来源:https://stackoverflow.com/questions/60415007/resttemplate-convertor-stopped-working-by-adding-interceptor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!