您可以使用 aClientHttpRequestInterceptor
来实现您所需要的。
1)创建一个HeaderInterceptor
实施ClientHttpRequestInterceptor
。在此示例中,它从 ThreadLocal 获取 Authorization 和 Accept 标头并传播它们:
public class HeaderInterceptor implements ClientHttpRequestInterceptor{
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpHeaders headers = request.getHeaders();
List<String> authorization = HeaderThreadLocal.getAuthorization()
List<String> accept = HeaderThreadLocal.getAuthorization();
headers.addAll("Authorization", authorization);
headers.addAll("Accept", accept);
return execution.execute(request, body);
}
}
2)配置你的RestTemplate
bean添加头拦截器:
restTemplate.getInterceptors().add(new HeaderInterceptor());