Sending GET request with Authentication headers using restTemplate Sending GET request with Authentication headers using restTemplate java java

Sending GET request with Authentication headers using restTemplate


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.


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.


Here's a super-simple example with basic authentication, headers, and exception handling...

private HttpHeaders createHttpHeaders(String user, String password){    String notEncoded = user + ":" + password;    String encodedAuth = "Basic " + Base64.getEncoder().encodeToString(notEncoded.getBytes());    HttpHeaders headers = new HttpHeaders();    headers.setContentType(MediaType.APPLICATION_JSON);    headers.add("Authorization", encodedAuth);    return headers;}private void doYourThing() {    String theUrl = "http://blah.blah.com:8080/rest/api/blah";    RestTemplate restTemplate = new RestTemplate();    try {        HttpHeaders headers = createHttpHeaders("fred","1234");        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);        ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);        System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());    }    catch (Exception eek) {        System.out.println("** Exception: "+ eek.getMessage());    }}