I have a Java endpoint like this
@RequestMapping(method = RequestMethod.GET, value = "/{test}", produces = "application/app+json;version=1")
public ResponseEntity<List<Entity>> getEntity(@PathVariable Long test) {
return ........
}
Now am making call to this rest endpoint using restTempate via URIBuilder
String url = UriComponentsBuilder.fromHttpUrl(this.URL)
.path(API_URL)
.path("/{test}")
.buildAndExpand(test).toString(); //How to add Headers??
return Arrays.asList(restTemplate.getForObject(url, Entity[].class));
I am tryng to add the header on the rest endpoint call but not sure what is the right place to add it. Or is there any other right way of doing it ? please suggest
RestTemplate.getForObject()
method does not support setting headers. The solution is to use the RestTemplate.exchange()
method.
You can add headers:
String url = UriComponentsBuilder.fromHttpUrl(this.URL)
.path(API_URL)
.path("/{test}")
.buildAndExpand(test).toString();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("header-key", "header-value");
...
HttpEntity<String> httpEntity = new HttpEntity<>(null, httpHeaders);
ResponseEntity<Entity[]> response = restTemplate.exchange(
url, HttpMethod.GET, httpEntity, Entity[].class);
return Arrays.asList(response);