RestTemplate logging POST data

2020-02-26 10:32发布

问题:

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

回答1:

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.