java - 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
实例)?
解决方案
推荐阅读
- amazon-web-services - sts:假定角色无法访问在 vpc 内运行的 lambda
- c++ - 'void QAbstractButton::clicked(bool)' 受保护
- python - Postgres:新创建的用户无法使用数据库
- r - xts 将数据从 chr 转换为 numeric
- c++ - 当我尝试在 DllMain 中显示它时,我的对话框不显示
- java - 从 Oracle 函数调用 Java 函数
- c# - 当鼠标悬停在窗口上时,如何更改窗口的背景?
- c# - 在 Visual Studio 中设置但尚未绑定的断点
- python-3.x - matplotlib ylabel TypeError:“str”对象不可调用
- git - 获取 NPM 项目的最新 Git 标签