我正在使用spring AsyncRestTemplate
帮助器类开发异步REST客户端。
客户端需要在每个请求的 header 中发送 token 。
当使用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);
但是,如果由于某种原因需要更改基础客户端,则无法再使用此拦截器。
还有其他方法可以使用与基础HTTP客户端无关的拦截器来拦截
AsyncClientHttpRequest
吗? 最佳答案
不,不是通过AsyncRestTemplate
也不通过HttpAsyncClient
。这些接口(interface)均未提供用于添加HttpRequestInterceptor
实例的转换器。
据我所知,只有这些构建器是可变的。因此,即使您可以获取请求工厂或客户端,也仍然无法更改它们。
您必须拦截他们的实际创建,这可能取决于您的设置。
关于java - 如何使用AsyncRestTemplate拦截AsyncClientHttpRequest?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26176685/