我正在使用RestTemplate调用Web服务。如何在Spring RestTemplate中记录响应?
String userId = restTemplate.getForObject(createUserUrl, String.class);
如果这不能返回用户ID我只是返回null,但我不知道为什么。如何将实际的XML响应输出到日志中?
我正在使用RestTemplate调用Web服务。如何在Spring RestTemplate中记录响应?
String userId = restTemplate.getForObject(createUserUrl, String.class);
如果这不能返回用户ID我只是返回null,但我不知道为什么。如何将实际的XML响应输出到日志中?
取决于哪个让你使用的HTTP连接的方法,你可以看看实际的HTTP连接类中调高记录。
例如,如果您使用的是公共HttpClient的,你可以设置
log4j.logger.httpclient.wire=DEBUG
公地httpclient的项目有an entire page in the documentation on their logging practices。
配置你的日志如下:
log4j.logger.org.springframework.web.client=DEBUG
然后使用curl命令查看输出,如
curl -H 'Accept: application/xml' -H 'Content-Type: application/xml' http://localhost:8080/ser/data
默认情况下,restTemplate使用HttpURLConnection的(通过SimpleClientHttpRequest),所以你可能需要切换到jakarta httpclient以查看日志语句。否则上面的日志配置会显示出你的反应
<bean id="httpClientFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory">
<constructor-arg><bean class="org.apache.commons.httpclient.HttpClient"/></constructor-arg>
</bean>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="httpClientFactory"/>
<property name="messageConverters">
...
log4j设置记录请求但不记录响应。我无法使用curl,因为它是一个Windows环境,另外我正在寻找一些我可以作为代码库的一部分提交的内容,以便为我们的集成测试启用日志记录。 – rjsang 2010-10-11 15:32:30
有curl的Windows版本,还有cygwin版本:http://curl.haxx.se/download.html#Win32 – 2010-10-11 17:25:46
您可以使用spring-rest-template-logger来记录RestTemplate
HTTP流量。
添加依赖于你的Maven项目:
<dependency>
<groupId>org.hobsoft.spring</groupId>
<artifactId>rest-template-logger</artifactId>
<version>0.1.0</version>
</dependency>
然后自定义您的RestTemplate
如下:
RestTemplate restTemplate = new RestTemplateBuilder()
.customizers(new LoggingCustomizer())
.build()
现在所有RestTemplate HTTP流量将在调试级别记录到org.hobsoft.spring.resttemplatelogger.LoggingCustomizer
。
免责声明:我写了这个库。
虽然这个链接可能回答这个问题,但最好在这里包含答案的重要部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/17802986) – 2017-11-01 10:53:09
@ Al-Mothafar谢谢,我在这里包含了相关信息。 – 2017-11-01 11:41:01
什么XML响应? – skaffman 2010-10-08 15:39:32
您还可以使用LoggingRequestInterceptor CF http://stackoverflow.com/a/22620168/409784 – Francois 2015-01-28 16:05:28
解决https://stackoverflow.com/questions/7952154/spring-resttemplate-how-to-enable-full- debug-logging-of-requests-responses/47467572 – user2746033 2017-11-24 06:43:15