[英]How to make restTemplate.getForObject call for Mediatypes Rest endpoint
I have a Java endpoint like this我有一个像这样的 Java 端点
@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现在我通过 URIBuilder 使用 restTempate 调用这个 rest 端点
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.我正在尝试在 rest 端点调用上添加 header,但不确定添加它的正确位置。 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.无法通过调用getForObject
方法发送自定义标头。 Instead, you can use the exchange
method.相反,您可以使用exchange
方法。
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. RestTemplate.getForObject()
方法不支持设置标题。 The solution is to use the RestTemplate.exchange()
method.解决方案是使用RestTemplate.exchange()
方法。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.