Setting custom header on Spring RestTemplate GET call

10,391

Solution 1

To pass a custom attribute in REST request via request Header, we need to create a new HTTPHeaders object and set the key and value by set method and pass to HttpEntity as shown below.

Next RestTemplate, exchange() method can be which has a method param of HttpEntity.

 HttpHeaders headers = new HttpHeaders();
 headers.set("custom-header-key","custom-header-value");
 HttpEntity<String> entity = new HttpEntity<>("paramters",headers);

 RestTemplate restTemplate = new RestTemplate();
 ResponseEntity<ResponseObj> responseObj = restTemplate.exchange("<end point url>", HttpMethod.GET,entity,ResponseObj.class);
 ResponseObj resObj = responseObj.getBody();

Solution 2

Try something like this

HttpHeaders createHeaders(String username, String password){

   return new HttpHeaders() {{

         String auth = username + ":" + password;

         byte[] encodedAuth = Base64.encodeBase64( 

            auth.getBytes(Charset.forName("US-ASCII")) );

         String authHeader = "Basic " + new String( encodedAuth );

         set( "Authorization", authHeader );

    }};

}

I hope it will help you :)

Share:
10,391
Sujit
Author by

Sujit

A Java backend developer by profession and do coding, design and architecting systems. Curious to learn and try out new technologies.

Updated on July 11, 2022

Comments

  • Sujit
    Sujit almost 2 years

    I am using Spring REST Template to call an external public REST API. As part of the API authentication I need send the user-key in the header. I am not sure how to set the custom header attribute in Spring REST template GET call.

    RestTemplate restTemplate = new RestTemplate();
    <Class> object = restTemplate.getForObject("<url>","<class type>");
    

    I found this can be done with HttpHeaders class by setting set("key","value") but didn't find any concrete example. Let me know if you have any info.

  • Sujit
    Sujit about 6 years
    Actually I found that we can use restTemplate.exchange method and get the response object from the body and cast to object. I will update in answering my question.