Reputation: 476
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.
Upvotes: 3
Views: 14255
Reputation: 4738
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 :)
Upvotes: 2
Reputation: 476
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();
Upvotes: 9