Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending GET request with Authentication headers using restTemplate

I need to retrieve resources from my server by sending a GET request with some Authorization headers using RestTemplate.

After going over the docs I noticed that none of the GET methods accepts headers as a parameter, and the only way to send Headers such as accept and Authorization is by using the exchange method.

Since it is a very basic action I am wondering if I am missing something and there another, easier way to do it?

like image 522
special0ne Avatar asked Jan 13 '14 21:01

special0ne


People also ask

How do you pass token in header using RestTemplate?

Setting bearer token for a GET request RestTemplate restTemplate = new RestTemplate(); String customerAPIUrl = "http://localhost:9080/api/customer"; HttpHeaders headers = new HttpHeaders(); headers. set("Authorization", "Bearer " + accessToken); //accessToken can be the secret key you generate. headers.

How do you get a RestTemplate header?

To add custom request headers to an HTTP GET request, you should use the generic exchange() method provided by the RestTemplate class.


2 Answers

You're not missing anything. RestTemplate#exchange(..) is the appropriate method to use to set request headers.

Here's an example (with POST, but just change that to GET and use the entity you want).

Here's another example.

Note that with a GET, your request entity doesn't have to contain anything (unless your API expects it, but that would go against the HTTP spec). It can be an empty String.

like image 66
Sotirios Delimanolis Avatar answered Sep 21 '22 04:09

Sotirios Delimanolis


You can use postForObject with an HttpEntity. It would look like this:

HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", "Bearer "+accessToken);  HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers); String result = restTemplate.postForObject(url, entity, String.class); 

In a GET request, you'd usually not send a body (it's allowed, but it doesn't serve any purpose). The way to add headers without wiring the RestTemplate differently is to use the exchange or execute methods directly. The get shorthands don't support header modification.

The asymmetry is a bit weird on a first glance, perhaps this is going to be fixed in future versions of Spring.

like image 20
iwein Avatar answered Sep 19 '22 04:09

iwein