如何在Spring RestTemplate中记录响应?

我正在使用RestTemplate来调用Web服务。

String userId = restTemplate.getForObject(createUserUrl, String.class); 

如果这不能返回用户ID我只是返回null但我不知道为什么。 如何将实际的XML响应输出到日志?

根据您使用的HTTP连接的方法,您可以查看实际HTTP连接类中的日志记录。

例如,如果您使用公共HttpClient,则可以设置

 log4j.logger.httpclient.wire=DEBUG 

commons-httpclient项目在其日志记录实践的文档中有一整页 。

按如下方式配置日志记录:

 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才能看到日志语句。 否则,上面的日志配置将显示响应

        ... 

您可以使用spring-rest-template-logger记录RestTemplate HTTP流量。

为Maven项目添加依赖项:

  org.hobsoft.spring spring-rest-template-logger 2.0.0  

然后按如下方式自定义RestTemplate

 RestTemplate restTemplate = new RestTemplateBuilder() .customizers(new LoggingCustomizer()) .build() 

现在,所有RestTemplate HTTP流量都将在调试级别记录到org.hobsoft.spring.resttemplatelogger.LoggingCustomizer

免责声明:我写了这个库。