Sending GET request with Authentication headers using restTemplate

special0ne picture special0ne · Jan 13, 2014 · Viewed 187.5k times · Source

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

After going over the docs I noticed that none of the GET methods accept 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?

Answer

Sotirios Delimanolis picture Sotirios Delimanolis · Jan 13, 2014

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.