正如Section 33.1, “RestTemplate customization”描述的那样,你可以使用RestTemplateCustomizer
和RestTemplateBuilder
构建一个自定义的RestTemplate
,这是创建使用代理的RestTemplate
的推荐方式。
代理配置的确切细节取决于底层使用的客户端请求factory,这里有个示例演示HttpClient
配置的HttpComponentsClientRequestFactory
对所有hosts都使用代理,除了192.168.0.5
。
static class ProxyCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
HttpHost proxy = new HttpHost("proxy.example.com");
HttpClient httpClient = HttpClientBuilder.create()
.setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {
@Override
public HttpHost determineProxy(HttpHost target,
HttpRequest request, HttpContext context)
throws HttpException {
if (target.getHostName().equals("192.168.0.5")) {
return null;
}
return super.determineProxy(target, request, context);
}
}).build();
restTemplate.setRequestFactory(
new HttpComponentsClientHttpRequestFactory(httpClient));
}
}