Resttemplate getForEntity - Pass headers

后端 未结 1 1294
谎友^
谎友^ 2021-02-12 01:45

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.

相关标签:
1条回答
  • 2021-02-12 02:10

    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());
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题