HttpClient Spring Boot Starter

tl;dr: As Spring does not support the configuration of the Apache and OkHttp HttpClients, this starter provides a simple drop-in replacement that allows the configuration of timeouts and proxy servers.

Contents

Some month ago I needed to configure a proxy server for a Spring Boot application. None of the supported HttpClients provides an out-of-the-box configuration for this use-case, therefor I needed to implement a custom HttpClientFactory.

As this situation is quite common in enterprise projects, I took some time to implement an open-source starter that can be reused in other project. You can find the starter, documentation and an example project on GitHub1.

Usage & Configuration

The httpclient-spring-boot-starter adds configuration value to the HttpClients used by spring-cloud, feignClient and RestTemplate. The former ones work out of the box but RestTemplate needs a small code-change.

First of all you need to add the starter as a maven dependency:

<dependency>
  <groupId>de.dev.eth0.spring-boot.httpclient</groupId>
  <artifactId>httpclient-spring-boot-starter</artifactId>
</dependency>

The Spring Cloud Commons documentation2 explains how to choose which HttpClient you want to use by setting either spring.cloud.httpclientfactories.apache.enabled or spring.cloud.httpclientfactories.ok.enabled to true.

To enable the HttpClient in your FeignClients, you also need to set feign.okhttp.enabled or feign.httpclient.enabled.

For a RestTemplate, I suggest adding a ClientHttpRequestFactory supplier to the builder:

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder, 
                        ClientHttpRequestFactory clientHttpRequestFactory) {
  return builder.requestFactory(() -> clientHttpRequestFactory).build();
}

Right now all requests are processed by the custom HttpClient and any configuration is taken into account.

Footnotes


  1. GitHub: HttpClient Spring Boot Starter

  2. Spring Cloud Commons: http-clients

Tags

Comments

Related