Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resttemplate getForEntity - Pass headers

Is it possible to set header as part of getForEntity method or should I use exchange? I am trying to set oauth header as part of getForEntity calls.

like image 685
Punter Vicky Avatar asked May 10 '17 18:05

Punter Vicky


People also ask

How do you pass the header in RestTemplate?

RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers. setAccept(Collections. singletonList(MediaType. APPLICATION_JSON)); HttpEntity<String> httpEntity = new HttpEntity<>("some body", headers); restTemplate.

What is difference between getForObject and getForEntity?

For example, the method getForObject() will perform a GET and return an object. getForEntity() : executes a GET request and returns an object of ResponseEntity class that contains both the status code and the resource as an object. getForObject() : similar to getForEntity() , but returns the resource directly.

How do you set HttpEntity headers?

To answer this question, you can use one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders. (You can also sepecify the HTTP method you want to use). RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders();

What is RestTemplate getForEntity?

The getForEntity method retrieves resources from the given URI or URL templates. It returns response as ResponseEntity using which we can get response status code, response body etc. To fetch data on the basis of some key properties, we can send them as path variables.


1 Answers

You can use .exchange:

ResponseEntity<YourResponseObj> entity = new TestRestTemplate().exchange(                 "http://localhost:" + port + "/youruri", HttpMethod.GET, new HttpEntity<Object>(headers),                 YourResponseObj.class); 

Full Junit sample:

@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class ReferenceTablesControllerTests {      @LocalServerPort     private int port;      @Test     public void getXxxx() throws Exception {         MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();         headers.add("Content-Type", "application/json");         headers.add("Authorization", "tokenxxx");         ResponseEntity<YourResponseObj> entity = new TestRestTemplate().exchange(                 "http://localhost:" + port + "/youruri", HttpMethod.GET, new HttpEntity<Object>(headers),                 YourResponseObj.class);         Assert.assertEquals(HttpStatus.OK, entity.getStatusCode());         Assert.assertEquals("foo", entity.getBody().getFoo());     }  } 
like image 162
Stéphane GRILLON Avatar answered Sep 30 '22 14:09

Stéphane GRILLON