RestTemplate with ClientHttpRequestInterceptor cau

2019-02-19 21:33发布

问题:

I am using a ClientHttpRequestInterceptor to add a Basic Authorization header to every request made by the RestTemplate in my Android project. I am also compressing 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; compressing 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 behaviour and I have not found anyone else reporting this problem, so is there a problem with my Interceptor implementation? I can work around the problem by setting the Content-Encoding header at the point I set the Authorization header, but this isn't desirable

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