我正在使用spring AsyncRestTemplate
helper类开发一个异步REST客户端.
客户端需要在每个请求的标头中发送令牌.
使用HttpAsyncClient
(http://hc.apache.org/httpcomponents-asyncclient-4.0.x/index.html)作为其余模板的基础http客户端时,可以添加拦截器:
HttpRequestInterceptor interceptor = (request, context) -> request.addHeader("token", "value");
CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.addInterceptorLast(interceptor)
.build();
HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory(client);
AsyncRestTemplate template = new AsyncRestTemplate(factory);
Run Code Online (Sandbox Code Playgroud)
但是,如果由于某种原因我需要更改底层客户端,则不能再使用此拦截器.
是否有任何其他方法来拦截AsyncClientHttpRequest
使用基础http客户端的拦截器不可知?
不,不通过AsyncRestTemplate
也不通过HttpAsyncClient
。这些接口都不提供用于添加HttpRequestInterceptor
实例的修改器。
据我所知,只有这些的构建器是可变的。因此,即使您可以获得请求工厂或客户端,您仍然无法更改它们。
您必须拦截它们的实际创建,这可能是不可能的,具体取决于您的设置。