java 如何在Spring RestTemplate中记录响应?

mwyxok5s  于 12个月前  发布在  Java
关注(0)|答案(6)|浏览(117)

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

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

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

s2j5cfk0

s2j5cfk01#

根据您使用的HTTP连接方法,您可以查看在实际的HTTP连接类中打开日志记录。
例如,如果您正在使用commons HttpClient,则可以设置

log4j.logger.httpclient.wire=DEBUG

commons-httpclient项目有an entire page in the documentation on their logging practices

q5lcpyga

q5lcpyga2#

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

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

<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">
...
nbysray5

nbysray53#

您可以使用spring-rest-template-logger记录RestTemplate HTTP流量。
在Maven项目中添加依赖项:

<dependency>
    <groupId>org.hobsoft.spring</groupId>
    <artifactId>spring-rest-template-logger</artifactId>
    <version>2.0.0</version>
</dependency>

然后按如下方式自定义您的RestTemplate

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

确保在application.properties中启用了调试日志记录:

logging.level.org.hobsoft.spring.resttemplatelogger.LoggingCustomizer = DEBUG

现在,所有RestTemplate HTTP流量都将在调试级别记录到org.hobsoft.spring.resttemplatelogger.LoggingCustomizer
作者:我写了这个图书馆。

3df52oht

3df52oht4#

如果你使用swagger来生成基于RestTemplate的客户端,那么在ApiClient中有一个公共方法setDebugging,你可以设置为true或false,然后我就可以看到发生了什么。希望这对你有帮助。我用最新的swager发电机CLI我认为它的2.9或东西

piztneat

piztneat5#

对于Apache HttpClient v4工厂:

final RestTemplate restTemplate = restTemplateBuilder
    .requestFactory(() -> new HttpComponentsClientHttpRequestFactory())
    .build();

Apache库具有:

public class ManagedHttpClientConnectionFactory
...
    private final Log log = LogFactory.getLog(DefaultManagedHttpClientConnection.class);
    private final Log headerLog = LogFactory.getLog("org.apache.http.headers");
    private final Log wireLog = LogFactory.getLog("org.apache.http.wire");

所以在DEBUG级别定义记录器org.apache.http.headersorg.apache.http.wire

lnlaulya

lnlaulya6#

你不需要写一行代码,你只需要在application.properties文件中添加以下属性

logging.level.org.springframework.web.client.RestTemplate=DEBUG

使用这个,它将在调试模式下记录rest模板调用的请求体、请求头、请求URL和响应体。

相关问题