如何在Spring RestTemplate中记录响应?

rjs*_*ang 14 java rest logging spring

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

String userId = restTemplate.getForObject(createUserUrl, String.class);
Run Code Online (Sandbox Code Playgroud)

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

mat*_*t b 11

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

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

log4j.logger.httpclient.wire=DEBUG
Run Code Online (Sandbox Code Playgroud)

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


sur*_*ajz 9

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

log4j.logger.org.springframework.web.client=DEBUG
Run Code Online (Sandbox Code Playgroud)

然后使用curl命令查看输出,例如

curl  -H 'Accept: application/xml' -H 'Content-Type: application/xml' http://localhost:8080/ser/data
Run Code Online (Sandbox Code Playgroud)

默认情况下,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">
...
Run Code Online (Sandbox Code Playgroud)

  • log4j设置记录请求但不记录响应.我不能使用curl,因为它是一个Windows环境,而且我正在寻找我可以作为代码库的一部分提交的东西,以便为我们的集成测试启用日志记录 (3认同)

归档时间:

查看次数:

28009 次

最近记录:

6 年,12 月 前