我有一种情况需要拦截请求,并且需要在该请求中设置授权 header 。 所以我得到了解决方案,我可以使用拦截器来设置该 header ,但是当我检查 AsyncRestTemplate 时,它没有像 RestTemplate 这样的属性。
是否有任何特定原因不包括该属性?
最佳答案
AsyncRestTemplate
扩展了 InterceptingAsyncHttpAccessor
抽象类,它公开了方法 setInterceptors
。所以你当然可以设置拦截器,就像你对非异步 RestTemplate 所做的那样。请注意,您的拦截器需要改为实现 AsyncClientHttpRequestInterceptor
:
public class AsyncFooBarInterceptor implements AsyncClientHttpRequestInterceptor {
@Override
public ListenableFuture<ClientHttpResponse> intercept(HttpRequest request, byte[] body, AsyncClientHttpRequestExecution execution) throws IOException {
return null; // do your thing instead
}
}
然后使用它:
AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
asyncRestTemplate.setInterceptors(Collections.singletonList(new AsyncFooBarInterceptor()));
关于spring - 为什么 spring 中的 AsyncRestTemplate 没有像 RestTemplate 这样的拦截器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43653418/