001/* 002 * Copyright 2012-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.docs.web.client; 018 019import org.apache.http.HttpException; 020import org.apache.http.HttpHost; 021import org.apache.http.HttpRequest; 022import org.apache.http.client.HttpClient; 023import org.apache.http.impl.client.HttpClientBuilder; 024import org.apache.http.impl.conn.DefaultProxyRoutePlanner; 025import org.apache.http.protocol.HttpContext; 026 027import org.springframework.boot.web.client.RestTemplateCustomizer; 028import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; 029import org.springframework.web.client.RestTemplate; 030 031/** 032 * Example configuration for using a {@link RestTemplateCustomizer} to configure a proxy. 033 * 034 * @author Andy Wilkinson 035 */ 036public class RestTemplateProxyCustomizationExample { 037 038 /** 039 * A {@link RestTemplateCustomizer} that applies an HttpComponents-based request 040 * factory that is configured to use a proxy. 041 */ 042 // tag::customizer[] 043 static class ProxyCustomizer implements RestTemplateCustomizer { 044 045 @Override 046 public void customize(RestTemplate restTemplate) { 047 HttpHost proxy = new HttpHost("proxy.example.com"); 048 HttpClient httpClient = HttpClientBuilder.create() 049 .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { 050 051 @Override 052 public HttpHost determineProxy(HttpHost target, 053 HttpRequest request, HttpContext context) 054 throws HttpException { 055 if (target.getHostName().equals("192.168.0.5")) { 056 return null; 057 } 058 return super.determineProxy(target, request, context); 059 } 060 061 }).build(); 062 restTemplate.setRequestFactory( 063 new HttpComponentsClientHttpRequestFactory(httpClient)); 064 } 065 066 } 067 // end::customizer[] 068 069}