我正在使用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/

10-11 22:26
查看更多