62

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.

Punter Vicky
  • 15,954
  • 56
  • 188
  • 315
  • 9
    you have to use exchange. If you look at the docs https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html, getForEntity doesn't take Object or HttpEntity as argument – pvpkiran May 10 '17 at 20:07
  • Thanks @pvpkiran – Punter Vicky May 16 '17 at 20:43

1 Answers1

84

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

}
Stéphane GRILLON
  • 11,140
  • 10
  • 85
  • 154
  • 1
    Thanks for this. Its good but as far as test rest template goes, this is absolutely nothing short of awful, I can't believe in 2022, people are making libraries with such verbose code just to pass headers to a request. Even the code isn't intuitive –  Apr 24 '22 at 13:36
  • 1
    @theMyth, first the code dates from 2017. second, the example is a unit test for understanding on stackoverflow but it can be used in your code if you code a framework for example :) – Stéphane GRILLON Apr 25 '22 at 15:18
  • Thank you. Yes that is true, I am trying this for my dissertation –  Apr 25 '22 at 15:42