【问题标题】:Resttemplate getForEntity - Pass headersResttemplate getForEntity - 传递标头
【发布时间】:2017-05-10 18:58:25
【问题描述】:
是否可以将标头设置为 getForEntity 方法的一部分,还是应该使用交换?我正在尝试将 oauth 标头设置为 getForEntity 调用的一部分。
【问题讨论】:
标签:
java
spring
resttemplate
【解决方案1】:
你可以使用.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());
}
}