java – 在Android Spring Interceptor中读取响应主体

我正在使用一个简单的Spring Interceptor类来记录我的Android应用程序中RestTemplate对象的所有REST请求/响应.到目前为止一切正常.

public class LoggerInterceptor implements ClientHttpRequestInterceptor {

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
  ClientHttpRequestExecution execution) throws IOException {

Log.d(TAG, "Request body: " + new String(body));
// ...more log statements...

ClientHttpResponse response = execution.execute(request, body);

Log.d(TAG, "Response Headers: " + response.getHeaders());

return response;
}

初始化时我打电话给:

List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
LoggerInterceptor loggerInterceptor = new LoggerInterceptor();
interceptors.add(loggerInterceptor);
restTemplate.setInterceptors(interceptors);

但是我无法在上面的方法中记录response.getBody(),因为InputStream被消耗一次并在稍后再次使用时抛出IllegalStateException.有没有解决方法,以便我也可以记录响应正文?

要允许多个response.getBody()调用将您的ClientHttpRequestFactory包装在BufferingClientHttpRequestFactory中.

ClientHttpRequestFactory requestFactory = 
    new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
restTemplate.setRequestFactory(requestFactory);
翻译自:https://stackoverflow.com/questions/11119487/read-the-response-body-in-an-android-spring-interceptor

转载注明原文:java – 在Android Spring Interceptor中读取响应主体