programing

Resttemplate getForEntity - 헤더 전달

bestprogram 2023. 10. 24. 21:29

Resttemplate getForEntity - 헤더 전달

getForEntity 메서드의 일부로 헤더를 설정할 수 있습니까? 아니면 교환을 사용해야 합니까?getForEntity 호출의 일부로 oauth 헤더를 설정하려고 합니다.

사용가능.exchange:

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

전체 주닛 샘플:

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

}

언급URL : https://stackoverflow.com/questions/43900699/resttemplate-getforentity-pass-headers