Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestTemplate vs Apache Http Client for production code in spring project

we have a Spring project that is about to go into production. Currently, the project is using Apache Http Client. There is a thought of using RestTemplate as HttpClient.

I am digging around to see any notable advantage of using RestTemplate over Apache's. Also, it would be interesting to know what HTTP transport does RestTemplate in its implementation. Apache Http Client has been used by several groups for many years and has a good reputation.

would we be risking moving to RestTemplate?

Further, this blog points that RestTemplate needs to be configured for production, although the configuration is minimal.

Thanks

like image 460
brain storm Avatar asked Jul 17 '15 20:07

brain storm


People also ask

What is the difference between RestTemplate and HttpClient?

HttpClient is a general-purpose library to communicate using HTTP, whereas RestTemplate is a higher-level abstraction, dealing with JSON/XML transformation of entities, etc. RestTemplate delegates to a ClientHttpRequestFactory, and one of the implementations of this interface uses Apache's HttpClient.

Does spring RestTemplate use Apache HttpClient?

Spring RestTemplate Configuration HttpComponentsClientHttpRequestFactory is ClientHttpRequestFactory implementation that uses Apache HttpComponents HttpClient to create requests.

What can I use instead of RestTemplate?

WebClient is part of Spring WebFlux and is intended to replace the classic RestTemplate. Compared to RestTemplate , WebClient has a more functional feel and is fully reactive. Since Spring 5.0, RestTemplate is deprecated.

Is RestTemplate going to be deprecated?

RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it's not really that future proof.


1 Answers

RestTemplate and HttpClient don't operate at the same abstraction level.

HttpClient is a general-purpose library to communicate using HTTP, whereas RestTemplate is a higher-level abstraction, dealing with JSON/XML transformation of entities, etc.

RestTemplate delegates to a ClientHttpRequestFactory, and one of the implementations of this interface uses Apache's HttpClient.

So, if the goal is to communicate with a Restful API, and you still want to use HttpClient, you can use RestTemplate over HttpClient.

Note that what I just said is exactly what the blog you linked to explains:

So, the solution is to use the org.springframework.http.client.HttpComponentsClientHttpRequestFactory, which is a ClientHttpRequestFactory delegating the creation of the requests to an HttpClient.

like image 116
JB Nizet Avatar answered Oct 09 '22 02:10

JB Nizet