RestTemplate with ClientHttpRequestInterceptor causes GZIP compression in half

I am using ClientHttpRequestInterceptor to add Basic Authorization header to every request made by RestTemplate in my Android project. I also compress the request body by setting the Content-Encoding header to "gzip" Adding an interceptor to the RestTemplate causes the request.execute method to be called twice; squeezing the body twice.

interceptor:

public class BasicAuthRequestInterceptor implements ClientHttpRequestInterceptor {

/** The base64 encoded credentials */
private final String encodedCredentials;

public BasicAuthRequestInterceptor(final String username, final String password) {
    this.encodedCredentials = new String(Base64.encodeBytes((username + ":" + password).getBytes()));
}

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

    HttpHeaders headers = request.getHeaders();
    headers.add("Authorization", "Basic " + this.encodedCredentials);

    return execution.execute(request, body);
}

}

      

RestTemplate setup:

// Create a new rest template
final RestTemplate restTemplate = new RestTemplate(requestFactory);

// Add authorisation interceptor
final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new BasicAuthRequestInterceptor(HTTP_AUTH_USERNAME, HTTP_AUTH_PASSWORD));
restTemplate.setInterceptors(interceptors);

      

I don't think this is the expected behavior and I haven't found anyone else to report this issue, so is there a problem with my Interceptor implementation? I can work around the problem by setting the Content-Encoding header where I set the Authorization header, but this is not desirable.

This is using the 1.0.1.RELEASE version of the spring-android-rest-template dependency.

+2


source to share





All Articles