Spring RestTemplate Request & Response Logging

It's sometimes useful to log HTTP requests and responses when working with a Spring RestTemplate. If you need fine-grained control over exactly what's logged you can use a custom interceptor to add logging before and after the remote call. Creating an Interceptor You'll need to create a class that extends ClientHttpRequestInterceptor and implement the intercept method as shown below. @Slf4j @Component public class LoggingInterceptor implements ClientHttpRequestInterceptor { @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; } private void logRequest(HttpRequest request, byte[] body) throws IOException { if (log.isDebugEnabled()) { log.debug("===========================request begin================================================"); log.debug("URI [...]

By |2019-12-17T22:17:46+00:00December 17th, 2019|RestTemplate, Spring|0 Comments

Configuring a Custom ObjectMapper for Spring RestTemplate

Configuring a Custom ObjectMapper for Spring RestTemplate One of the great things about RestTemplate is its simplicity. You simply instantiate it like this... RestTemplate restTemplate = new RestTemplate(); and off you go. Under the hood Spring automatically creates and registers a number of message converters to handle various data formats for requests and responses.  A MappingJackson2HttpMessageConverter uses Jackson to map POJOs to JSON and vice versa. When the MappingJackson2HttpMessageConverter is created it's given a new instance of ObjectMapper. A default instance of ObjectMapper is fine is many case but there are times when you might want to customise the ObjectMapper used.  For example, I ran into [...]

By |2019-12-03T07:49:16+00:00December 3rd, 2019|RestTemplate|0 Comments