I am trying to get ClientHttpRequestInterceptor working following, Baeldung's Spring RestTemplate Request/Response Logging. The problem is the ClientHttpRequestInterceptor never gets called.
I had a similar issue with a HandlerInterceptor and a HandlerInterceptorAdapter interceptors. The issue was I needed a add a listener, that 99% of the article I found did not mention.
@Configuration
public class ListenerConfig implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext sc) throws ServletException {
sc.addListener(new RequestContextListener());
}
}
I am guessing something about Spring has changed and the listeners are not there by default.
Does anyone know the listener for ClientHttpRequestInterceptor?
The interceptor:
public class LoggingInterceptor implements ClientHttpRequestInterceptor {
static Logger LOGGER = LoggerFactory.getLogger(LoggingInterceptor.class);
@Override
public ClientHttpResponse intercept(
HttpRequest req, byte[] reqBody, ClientHttpRequestExecution ex) throws IOException {
LOGGER.debug("Request body: {}", new String(reqBody, StandardCharsets.UTF_8));
ClientHttpResponse response = ex.execute(req, reqBody);
InputStreamReader isr = new InputStreamReader(
response.getBody(), StandardCharsets.UTF_8);
String body = new BufferedReader(isr).lines()
.collect(Collectors.joining("\n"));
LOGGER.debug("Response body: {}", body);
return response;
}
}
RestClientConfig:
@Configuration
public class RestClientConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors
= restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<>();
}
interceptors.add(new LoggingInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
}
This may be related to ClientHttpRequestInterceptor not called in springboot.