Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read the response body in an Android Spring Interceptor

I'm using a simple Spring Interceptor class to log all REST requests/responses for the RestTemplate object in my Android app. So far everything works fine.

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;
}

At initialization I call:

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

However I cannot log response.getBody() in the method above because the InputStream gets consumed once and throws an IllegalStateException when it is consumed again later. Is there a way around this so that I can log the response body too?

like image 891
Nachi Avatar asked Jun 20 '12 12:06

Nachi


1 Answers

To allow for multiple response.getBody() calls wrap your ClientHttpRequestFactory in a BufferingClientHttpRequestFactory.

ClientHttpRequestFactory requestFactory = 
    new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
restTemplate.setRequestFactory(requestFactory);
like image 119
Jataro Avatar answered Nov 12 '22 00:11

Jataro