Backend Development 13 min read

Mastering Spring RestTemplate: Core Methods, Configuration, and Advanced Usage

Learn how to use Spring's RestTemplate and WebClient for calling REST endpoints, explore their core methods, initialization options, URI handling, header and body processing, multipart support, and underlying HttpMessageConverters, with practical code examples and migration guidance for modern Spring applications.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Mastering Spring RestTemplate: Core Methods, Configuration, and Advanced Usage

Environment

Spring 5.3.23

REST Endpoints

Spring provides two options for calling REST endpoints:

RestTemplate The original synchronous Spring REST client with template method APIs.

WebClient A non‑blocking, reactive alternative that supports synchronous, asynchronous, and streaming scenarios.

Since version 5.0, RestTemplate is in maintenance mode and only receives critical bug fixes. It is recommended to use WebClient for a more modern API that supports sync, async, and streaming use cases.

RestTemplate Detailed Overview

RestTemplate offers a high‑level API for HTTP client operations, making one‑line REST calls easy. Core methods include:

getForObject : Perform a GET request and retrieve the response body.

getForEntity : Perform a GET request and obtain a ResponseEntity containing status, headers, and body.

headForHeaders : Retrieve all headers using a HEAD request.

postForLocation : Create a new resource with POST and return the Location header.

postForObject : Create a new resource with POST and return the response body.

postForEntity : Create a new resource with POST and return a ResponseEntity .

put : Create or update a resource using PUT.

patchForObject : Update a resource with PATCH and return the response body.

delete : Delete a resource at the given URI.

optionsForAllow : Use an OPTIONS request to determine allowed HTTP methods.

exchange : A flexible version of the above methods that accepts a RequestEntity and can use ParameterizedTypeReference for generic response types.

execute : The most generic way to perform a request, giving full control via callbacks.

Initializing RestTemplate

The default constructor uses java.net.HttpURLConnection . You can switch to other HTTP libraries by providing a custom ClientHttpRequestFactory implementation, such as Apache HttpComponents, Netty, or OkHttp.

<code>RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());</code>

Each ClientHttpRequestFactory exposes configuration options specific to its underlying HTTP client (e.g., credentials, connection pools).

Note: The java.net implementation may throw exceptions for error status codes (e.g., 401). If this is an issue, switch to another HTTP client library.

URI Usage in RestTemplate

Many RestTemplate methods accept URI templates with variables, either as a var‑args list or a Map&lt;String,String&gt; .

<code>String result = restTemplate.getForObject("https://pack.com/hotels/{hotel}/bookings/{booking}", String.class, "42", "21");</code>
<code>Map&lt;String, String&gt; vars = Collections.singletonMap("hotel", "42");
String result = restTemplate.getForObject("https://pack.com/hotels/{hotel}/rooms/{hotel}", String.class, vars);</code>

URI templates are automatically encoded:

<code>restTemplate.getForObject("https://pack.com/hotel list", String.class); // requests https://example.com/hotel%20list</code>

You can customize encoding via the uriTemplateHandler property or pass a pre‑built java.net.URI instance.

Header Usage in RestTemplate

Use exchange() to set request headers:

<code>String uriTemplate = "https://pack.com/hotels/{hotel}";
URI uri = UriComponentsBuilder.fromUriString(uriTemplate).build(666);
RequestEntity<Void> requestEntity = RequestEntity.get(uri)
    .header("X-API-Version", "1")
    .build();
ResponseEntity<String> response = template.exchange(requestEntity, String.class);
String responseHeader = response.getHeaders().getFirst("MyResponseHeader");
String body = response.getBody();</code>

Various RestTemplate overloads returning ResponseEntity also expose response headers.

Body Processing in RestTemplate

Conversion between HTTP bodies and Java objects is handled by HttpMessageConverter implementations.

For POST requests, the request body is serialized automatically; the appropriate Content-Type is chosen based on the object type. You can override it via exchange() .

For GET requests, the response body is deserialized into the target type:

<code>Person person = restTemplate.getForObject("https://pack.com/people/{id}", Person.class, 66);</code>

The Accept header is also set automatically based on the expected response type, but can be overridden with exchange() .

By default, RestTemplate registers all built‑in message converters found on the classpath; you can customize the list as needed.

HttpMessageConverters

StringHttpMessageConverter : Reads/writes String instances; supports all text media types and writes text/plain .

FormHttpMessageConverter : Handles form data ( application/x-www-form-urlencoded ) and multipart/form-data when a MultiValueMap contains non‑string parts.

ByteArrayHttpMessageConverter : Reads/writes byte[] ; supports all media types, defaults to application/octet-stream .

MarshallingHttpMessageConverter : Uses Spring OXM marshaller/unmarshaller to read/write XML.

MappingJackson2HttpMessageConverter : Uses Jackson ObjectMapper for JSON; customizable via annotations or custom ObjectMapper .

MappingJackson2XmlHttpMessageConverter : Uses Jackson XML XmlMapper for XML; also customizable.

SourceHttpMessageConverter : Reads/writes javax.xml.transform.Source (DOMSource, SAXSource, StreamSource).

BufferedImageHttpMessageConverter : Reads/writes java.awt.image.BufferedImage .

You can restrict serialization to specific JSON views:

<code>MappingJacksonValue value = new MappingJacksonValue(new User("eric", "7!jd#h23"));
value.setSerializationView(User.WithoutPasswordView.class);
RequestEntity<MappingJacksonValue> requestEntity = RequestEntity.post(new URI("https://pack.com/user")).body(value);
ResponseEntity<String> response = template.exchange(requestEntity, String.class);</code>

Multipart Support with RestTemplate

To send multipart data, build a MultiValueMap&lt;String, Object&gt; where values can be plain objects, file resources, or HttpEntity with custom headers.

<code>MultiValueMap&lt;String, Object&gt; parts = new LinkedMultiValueMap<>();
parts.add("fieldPart", "fieldValue");
parts.add("filePart", new FileSystemResource("...logo.png"));
parts.add("jsonPart", new Person("Jason"));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
parts.add("xmlPart", new HttpEntity<>(myBean, headers));</code>

Usually you do not need to set a content type for each part; the appropriate HttpMessageConverter determines it automatically. If the map contains any non‑string values, FormHttpMessageConverter will set multipart/form-data ; otherwise it defaults to application/x-www-form-urlencoded .

<code>MultiValueMap<String, Object> parts = ...;
template.postForObject("https://pack.com/upload", parts, Void.class);</code>

End of guide.

JavaSpringHTTPRESTRestTemplateWebClient
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.