繁体   English   中英

Resttemplate getForEntity - 传递标题

[英]Resttemplate getForEntity - Pass headers

是否可以将标头设置为getForEntity方法的一部分,还是应该使用exchange? 我试图将oauth标头设置为getForEntity调用的一部分。

你可以使用.exchange

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

完整的Junit样本:

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM