Resttemplate getForEntity-通过标头 [英] Resttemplate getForEntity - Pass headers
本文介绍了Resttemplate getForEntity-通过标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将标头设置为getForEntity方法的一部分,还是应该使用交换?我正在尝试将oauth标头设置为getForEntity调用的一部分.
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.
推荐答案
您可以使用.exchange
:
ResponseEntity<YourResponseObj> entity = new TestRestTemplate().exchange(
"http://localhost:" + port + "/youruri", HttpMethod.GET, new HttpEntity<Object>(headers),
YourResponseObj.class);
完整的Junit示例:
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());
}
}
这篇关于Resttemplate getForEntity-通过标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文