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.
RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers. setAccept(Collections. singletonList(MediaType. APPLICATION_JSON)); HttpEntity<String> httpEntity = new HttpEntity<>("some body", headers); restTemplate.
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.
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();
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.
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()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With