为了记录请求和响应,我添加了一个 LoggingRequestInterceptor ,它实现了 ClientHttpRequestInterceptor ...
响应主体是一个流,如果我阅读了它的拦截器,它将无法用于TestRestTemplate将其反序列化为我的对象模型。换句话说,当我调用testRestTemplate.get…时,我将始终取回空对象(即使我看到该对象是我的回应)。
要解决RestTemplate的问题,可以使用 BufferingClientHttpRequestFactory 进行修复。我不知道如何为TestRestTemplate修复它...
我尝试将BufferingClientHttpRequestFactory添加到RestTemplate的实例,然后用该实例包装TestRestTemplate:
restTemplateBuilder.configure(restTemplate);
...但是根本没有日志记录。
这就是我添加日志记录拦截器的方式。
public static RestTemplateBuilder withInterceptors() {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new LoggingRequestInterceptor());
return new RestTemplateBuilder()
.interceptors(interceptors);
}
最后,我想: 1.记录响应正文 2.将其反序列化为对象模型(如果打开日志记录,则为null)
答案 0 :(得分:0)
调试请求/响应的最简单方法是在属性中进行设置:
logging.level.org.apache.http=DEBUG
并使用BufferingClientHttpResponseWrapper:
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LoggingRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
final ClientHttpRequestExecution execution) throws IOException {
ClientHttpResponse response = execution.execute(request, body);
response = log(request, body, response);
return response;
}
private ClientHttpResponse log(final HttpRequest request, final byte[] body, final ClientHttpResponse response) {
final ClientHttpResponse responseCopy = new BufferingClientHttpResponseWrapper(response);
logger.debug("Method: ", request.getMethod().toString());
logger.debug("URI: ", , request.getURI().toString());
logger.debug("Request Body: " + new String(body));
logger.debug("Response body: " + IOUtils.toString(responseCopy.getBody()));
return responseCopy;
}
}
并设置:
LoggingRequestInterceptor loggingInterceptor = new LoggingRequestInterceptor();
restTemplate.getInterceptors().add(loggingInterceptor);
答案 1 :(得分:0)
TestRestTemplate testRestTemplate = new TestRestTemplate();
testRestTemplate.getRestTemplate()
.setRequestFactory(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));