2

我正在使用 ClientHttpRequestInterceptor 为我的 Android 项目中 RestTemplate 发出的每个请求添加一个基本授权标头。我还通过将 Content-Encoding 标头设置为“gzip”来压缩请求正文向 RestTemplate 添加拦截器会导致 request.execute 方法被调用两次;压缩身体两次。

拦截器:

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

}

休息模板设置:

// 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);

我不认为这是预期的行为,我还没有发现其他人报告这个问题,所以我的拦截器实现有问题吗?我可以通过在设置 Authorization 标头时设置 Content-Encoding 标头来解决此问题,但这是不可取的

这是使用 spring-android-rest-template 依赖项的 1.0.1.RELEASE 版本。

4

0 回答 0