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
It's not possible to send custom headers by calling the getForObject
method. Instead, you can use the exchange
method.
The code would be something like this:
HttpHeaders headers = new HttpHeaders();
headers.add("HEADER", "VALUE");
HttpEntity<String> entity = new HttpEntity<>(null, headers);
restTemplate.exchange(url, HttpMethod.GET, entity, Entity[].class);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.