Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestTemplate logging POST data

my resttemplate.exchange() failed on a POST request, with the server returning a 500 error.

I tried to set the root logging level to DEBUG, but nothing was logged before the 500 error was returned. to make sure that my logging config is right, I added a line before the resttemplate call

HttpClient client = new DefaultHttpClient();
client.execute(new HttpGet("http://google.com"));

in this case indeed a lot of logging messages appeared.

so how can I make RestTemplate export the debugging data?

Thanks Yang

like image 992
teddy teddy Avatar asked May 15 '13 19:05

teddy teddy


People also ask

Why RestTemplate is deprecated?

RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it's not really that future proof. First, we create a Spring Boot project with the spring-boot-starter-web dependency.

How do you log a Spring rest request response?

Custom Request Logging Among the Spring request interceptors, one of the noteworthy interfaces is HandlerInterceptor, which we can use to log the incoming request by implementing the following methods: preHandle() – we execute this method before the actual controller service method.

Is RestTemplate synchronous or asynchronous?

RestTemplate uses Java Servlet API and is therefore synchronous and blocking. Conversely, WebClient is asynchronous and will not block the executing thread while waiting for the response to come back.


1 Answers

From your analysis it seems that you expect RestTemplate to use Apache HttpClient.

However, by default, Spring RestTemplate does not use Apache HttpClient but uses the JDK facilities (java.net.URL#openConnection() etc.) by means of SimpleClientHttpRequestFactory.

org.springframework.http.client.support.HttpAccessor declares:

private ClientHttpRequestFactory requestFactory = new
SimpleClientHttpRequestFactory();

As far as I know, this client does not support logging requests/responses.

To change RestTemplate to use HttpClient, try this:

new RestTemplate(new HttpComponentsClientHttpRequestFactory());

Logging configuration should then enable category org.apache.http.wire at level debug for complete requests/responses to be logged.

like image 173
Geert Avatar answered Sep 28 '22 01:09

Geert