Introduction

RestTemplate is one of the most commonly used tools for REST service invocation. In this tutorial, we'll show through simple code examples how to add headers to RestTemplate in Spring. It's simple and it's based on using RestTemplate methods that are able to accept HttpHeaders. 

How to add headers to RestTemplate in Spring?

What we recommend here is to use one of the exchange methods that are able to accept HttpEntity where we're able to set HttpHeaders (for example, Authorization, Accept, Content-Type, etc.). Also, by using one of the exchange methods, we're able to sett Http method we would like to use.

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> httpEntity = new HttpEntity<>("some body", headers);
restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);

 Instead of setting headers by using dedicated methods (like setAccept in previous code), you can use general set (headerName, headerValue)  method.

headers.set("Accept", "application/json");

It's also possible to pass HttpEntity as request argument to method postForObject like in the following sample ( for more details check RestTemplate documentation for postForObject):

HttpEntity<String> entity = new HttpEntity<>("some body", headers);
restTemplate.postForObject(url, entity, String.class); 

Pin It

Newsletter

Please enable the javascript to submit this form