RestTemplate似乎保留了Authorization标头

时间:2020-08-26 11:10:08

标签: java spring spring-boot resttemplate

我正在使用Spring 4 RestTemplate进行一些服务器端API调用。

RestTemplate实例是使用如下创建的Apache HttpClient的自定义实例(不是Spring Boot的默认实例):

PoolingHttpClientConnectionManager cm;
...
CloseableHttpClient httpClient = HttpClients.custom()
                                            .setConnectionManager(cm)
                                            .build();

某些API调用使用HTTP基本身份验证,因此需要具有Authorization标头。我将其添加到RequestEntity上,然后在exchange()上执行RestTemplate调用,效果很好。

RequestEntity<Void> requestEntity;
requestEntity = RequestEntity.get(uri)
                             .accept(MediaType.valueOf("application/repository.folder+json"))
                             .acceptCharset(UTF_8)
                             .header("Accept-Encoding", "")
                             .header("Authorization", apiBasicAuthHeader())
                             .build();

(对同一后端服务器的)其他一些API调用不应使用HTTP基本认证,而应使用作为请求参数提供的预先认证的令牌。

RequestEntity<Void> requestEntity = RequestEntity.get(uriWithToken)
                                                 .accept(APPLICATION_JSON)
                                                 .acceptCharset(UTF_8)
                                                 .header("Accept-Encoding", "")
                                                 .build();

operations.exchange(requestEntity, ResourceLookupResults.class)

这本身也可以正常工作。

但是,如果我先使用Authorization标头进行API调用,然后尝试使用预先认证的令牌(使用相同的RestTemplate)进行API调用,似乎Authorization标头仍在第二个要求。我希望添加到RequestEntity的标头仅用于该特定请求,而不用于不需要它的后续请求。为什么会这样?避免这种情况的最佳方法是什么(例如使用单独的RestTemplate实例)?

0 个答案:

没有答案