Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

java - How to make restTemplate.getForObject call for Mediatypes Rest endpoint

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...