Skip to main content

77.1 Configure RestTemplate to Use a Proxy

77.1 配置RestTemplate使用代理

正如33.1 自定义RestTemplate描述的那样,你可以使用RestTemplateCustomizerRestTemplateBuilder构建一个自定义的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));
}

}