33.1 自定义RestTemplate

当使用RestTemplateBuilder构建RestTemplate时,可以通过RestTemplateCustomizer进行更高级的定制,所有RestTemplateCustomizer beans将自动添加到自动配置的RestTemplateBuilder。此外,调用additionalCustomizers(RestTemplateCustomizer…)方法可以创建一个新的,具有其他customizers的RestTemplateBuilder

以下示例演示使用自定义器(customizer)配置所有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. }