RestTemplate with ClientHttpRequestInterceptor causes GZIP compression twice

孤街浪徒 提交于 2019-12-19 10:32:37

问题


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.

来源:https://stackoverflow.com/questions/27047161/resttemplate-with-clienthttprequestinterceptor-causes-gzip-compression-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!