1. Overview
In this short tutorial, we’ll take a look at how to send a request to a proxy using RestTemplate.
2. Dependencies
First, the RestTemplateCustomizer uses the HttpClient class to connect to the proxy.
To use the class, we need to add Apache’s httpcore dependency to our Maven pom.xml file:
<dependency>
<groupId>org.apache.httpcomponents.core5</groupId>
<artifactId>httpcore5</artifactId>
<version>5.2.1</version>
</dependency>
Or to our Gradle build.gradle file:
compile 'org.apache.httpcomponents.core5:httpcore5:5.2.1'
3. Using SimpleClientHttpRequestFactory
Sending a request to a proxy using RestTemplate is pretty simple. All we need to do is to call the setProxy(java.net.Proxy) from SimpleClientHttpRequestFactory before building the RestTemplate object.
First, we start by configuring the SimpleClientHttpRequestFactory:
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(PROXY_SERVER_HOST, PROXY_SERVER_PORT));
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setProxy(proxy);
Then, we move forward to passing the request factory instance to the RestTemplate constructor:
RestTemplate restTemplate = new RestTemplate(requestFactory);
Finally, once we have built the RestTemplate, we can use it to make proxied requests:
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://httpbin.org/get", String.class);
assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK)));
4. Using RestTemplateCustomizer
Another approach is to use a RestTemplateCustomizer* with RestTemplateBuilder to build a customized *RestTemplate.
Let’s start defining a ProxyCustomizer:
class ProxyCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
HttpHost proxy = new HttpHost(PROXY_SERVER_HOST, PROXY_SERVER_PORT);
HttpClient httpClient = HttpClientBuilder.create()
.setRoutePlanner(new DefaultProxyRoutePlanner(proxy))
.build();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}
}
After that, we build our customized RestTemplate:
RestTemplate restTemplate = new RestTemplateBuilder(new ProxyCustomizer()).build();
And finally, we use the RestTemplate to make requests that pass first through a proxy:
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://httpbin.org/get", String.class);
assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK)));
5. Conclusion
In this short tutorial, we’ve explored two different ways to send a request to a proxy using RestTemplate.
First, we learned how to send the request through a RestTemplate built using a SimpleClientHttpRequestFactory. Then we learned how to do the same using a RestTemplateCustomizer, this one being the recommended approach according to the documentation.
As always, the code samples are available over on GitHub.