Resttemplate getForEntity - 传递标题

时间:2017-05-10 18:58:25

标签: java spring resttemplate

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

1 个答案:

答案 0 :(得分:14)

您可以使用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());
    }

}

Full Junit样本:

{{1}}