Log Request and Response With Spring RestTemplate
Log Request and Response With Spring RestTemplate
RestTemplate
https://howtodoinjava.com/spring-boot2/resttemplate/clienthttprequestinterceptor/
Current Time 0:00
/
Duration 1:45
RequestResponseLoggingInterceptor.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.nio.charset.Charset;
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException
{
logRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
logResponse(response);
return response;
}
@Bean
public RestTemplate restTemplate()
{
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new
BufferingClientHttpRequestFactory(clientHttpRequestFactory()));
restTemplate.setMessageConverters(Collections.singletonList(mappingJacksonH
ttpMessageConverter()));
restTemplate.setInterceptors( Collections.singletonList(new
RequestResponseLoggingInterceptor()) );
return restTemplate;
}
It is very important to note that we are allowed to read a response body only once. Next time
the body will be empty. So if we want to prevent this behavior, we must use the
BufferingClientHttpRequestFactory that buffers all outgoing and incoming streams in
memory.
4. Demo
Start the application and execute any REST API using RestTemplate. Observe the logs.
Happy Learning !!