82. HTTP Clients

Spring Boot offers a number of starters that work with HTTP clients. This section answers questions related to using them.

82.1 Configure RestTemplate to Use a Proxy

As described in Section 35.1, “RestTemplate Customization”, you can use a RestTemplateCustomizer with RestTemplateBuilder to build a customized RestTemplate. This is the recommended approach for creating a RestTemplate configured to use a proxy.

The exact details of the proxy configuration depend on the underlying client request factory that is being used. The following example configures HttpComponentsClientRequestFactory with an HttpClient that uses a proxy for all hosts except

static class ProxyCustomizer implements RestTemplateCustomizer {

	public void customize(RestTemplate restTemplate) {
		HttpHost proxy = new HttpHost("proxy.example.com");
		HttpClient httpClient = HttpClientBuilder.create().setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {

			public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context)
					throws HttpException {
				if (target.getHostName().equals("")) {
					return null;
				return super.determineProxy(target, request, context);

		restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));


82.2 Configure the TcpClient used by a Reactor Netty-based WebClient

When Reactor Netty is on the classpath a Reactor Netty-based WebClient is auto-configured. To customize the client’s handling of network connections, provide a ClientHttpConnector bean. The following example configures a 60 second read timeout and adds a ReadTimeoutHandler:

ClientHttpConnector clientHttpConnector(ReactorResourceFactory resourceFactory) {
	TcpClient tcpClient = TcpClient.create(resourceFactory.getConnectionProvider())
			.runOn(resourceFactory.getLoopResources()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60000)
			.doOnConnected((connection) -> connection.addHandlerLast(new ReadTimeoutHandler(60)));
	return new ReactorClientHttpConnector(HttpClient.from(tcpClient));

Note the use of ReactorResourceFactory for the connection provider and event loop resources. This ensures efficient sharing of resources for the server receiving requests and the client making requests.