Search code examples
resttemplatespring-rest

Setting custom header on Spring RestTemplate GET call


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.


Solution

  • 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();