The RestTemplate provides a high-level API over HTTP client libraries in the form of a classic Spring Template class.
It exposes the following groups of overloaded methods:
Initialization
RestTemplate uses the same HTTP library abstraction as RestClient.
By default, it uses the SimpleClientHttpRequestFactory, but this can be changed via the constructor.
See Client Request Factories.
Body
Objects passed into and returned from RestTemplate methods are converted to and from HTTP messages
with the help of an HttpMessageConverter, see HTTP Message Conversion.
Migrating to RestClient
Applications can adopt RestClient in a gradual fashion, first focusing on API usage and then on infrastructure setup.
You can consider the following steps:
-
Create one or more
RestClientfrom existingRestTemplateinstances, like:RestClient restClient = RestClient.create(restTemplate). Gradually replaceRestTemplateusage in your application, component by component, by focusing first on issuing requests. See the table below for API equivalents. -
Once all client requests go through
RestClientinstances, you can now work on replicating your existingRestTemplateinstance creations by usingRestClient.Builder. BecauseRestTemplateandRestClientshare the same infrastructure, you can reuse customClientHttpRequestFactoryorClientHttpRequestInterceptorin your setup. See theRestClientbuilder API.
If no other library is available on the classpath, RestClient will choose the JdkClientHttpRequestFactory
powered by the modern JDK HttpClient, whereas RestTemplate would pick the SimpleClientHttpRequestFactory that
uses HttpURLConnection. This can explain subtle behavior difference at runtime at the HTTP level.
The following table shows RestClient equivalents for RestTemplate methods.
RestTemplate method |
RestClient equivalent |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
RestClient and RestTemplate instances share the same behavior when it comes to throwing exceptions
(with the RestClientException type being at the top of the hierarchy).
When RestTemplate consistently throws HttpClientErrorException for "4xx" response statues,
RestClient allows for more flexibility with custom "status handlers".