首页 > 解决方案 > RestTemplate 似乎保留了 Authorization 标头

问题描述

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

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

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

一些 API 调用使用 HTTP 基本身份验证,因此需要有一个 Authorization 标头。我将其添加到 a 上RequestEntity,然后对 the 执行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实例)?

标签: javaspringspring-bootresttemplate

解决方案


推荐阅读