72.1 配置RestTemplate使用代理

正如Section 33.1, “RestTemplate customization”描述的那样,你可以使用RestTemplateCustomizerRestTemplateBuilder构建一个自定义的RestTemplate,这是创建使用代理的RestTemplate的推荐方式。

代理配置的确切细节取决于底层使用的客户端请求factory,这里有个示例演示HttpClient配置的HttpComponentsClientRequestFactory对所有hosts都使用代理,除了192.168.0.5

  1. static class ProxyCustomizer implements RestTemplateCustomizer {
  2. @Override
  3. public void customize(RestTemplate restTemplate) {
  4. HttpHost proxy = new HttpHost("proxy.example.com");
  5. HttpClient httpClient = HttpClientBuilder.create()
  6. .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {
  7. @Override
  8. public HttpHost determineProxy(HttpHost target,
  9. HttpRequest request, HttpContext context)
  10. throws HttpException {
  11. if (target.getHostName().equals("192.168.0.5")) {
  12. return null;
  13. }
  14. return super.determineProxy(target, request, context);
  15. }
  16. }).build();
  17. restTemplate.setRequestFactory(
  18. new HttpComponentsClientHttpRequestFactory(httpClient));
  19. }
  20. }