Changing HttpClient in Spring RestTemplate

If you’re a Spring boot user, you might have definitely used RestTemplate. If you read the official documentation carefully, you might read that RestTemplate will be deprecated in the future and we must use WebClient which offers Synchronous, Asynchronous and Streaming scenarios such as Server-Sent Events, WebSockets, etc. Majority of the applications in production uses RestTemplates and will be practically a long way before it is completely replaced with Reactive WebFlux. It is important to know how we can customize the RestTemplate changing different Http clients. The default HttpClient used in the RestTemplate is provided by the JDK. It is developed on top of the HttpURLConnection. There is a new module added in Java 9 in incubation status and standardized in Java 11 called java.net.http.HttpClient. We can use this to make a client connection as well without needing third-party libraries. It is still unclear whether this will be used in Spring clients. Let’s get back to the business. In Spring, the default HTTP client can be changed to Apache’s HttpClient or Square’s OkHttpClient. We can configure the RestTemplate to use the HttpClient of our choice. We can do this either directly or by using Spring Cloud Commons org.springframework.cloud.commons.httpclient which provides

Continue reading »