如何 restTemplate.getForObject 调用 Mediatypes Rest 端点

How to make restTemplate.getForObject call for Mediatypes Rest endpoint

我有一个 Java 这样的端点

 @RequestMapping(method = RequestMethod.GET, value = "/{test}", produces = "application/app+json;version=1")
public ResponseEntity<List<Entity>> getEntity(@PathVariable Long test) {
        
        return ........
    }

现在我通过 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));

我正在尝试在其余端点调用中添加 header,但不确定添加它的正确位置。 或者还有其他正确的方法吗?请推荐

无法通过调用 getForObject 方法发送自定义 headers。 相反,您可以使用 exchange 方法。

代码应该是这样的:

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() 方法。

您可以添加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);