HTTP get with headers using RestTemplate
The RestTemplate getForObject()
method does not support setting headers. The solution is to use the exchange()
method.
So instead of restTemplate.getForObject(url, String.class, param)
(which has no headers), use
HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...
HttpEntity<Void> requestEntity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.GET, requestEntity, String.class, param);
Finally, use response.getBody()
to get your result.
This question is similar to this question.
The getForObject() method of RestTemplate does not support setting headers. you can use this
syntax
:
restTemplate.exchange(url endpoint, HttpMethod.GET,entity, params)
public List<Employee> getListofEmployee()
{
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<List<Employee>> response = restTemplate.exchange("http://hello-server/rest/employees",
HttpMethod.GET,entity, new ParameterizedTypeReference<List<Employee>>() {});
return response.getBody(); //this returns List of Employee
}
Take a look at the JavaDoc for RestTemplate.
There is the corresponding getForObject
methods that are the HTTP GET equivalents of postForObject
, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.
Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange
methods allow you to provide an HttpEntity
object representing the details of the request (including headers). The execute
methods allow you to specify a RequestCallback
from which you can add the headers upon its invocation.