1
是否可以將標頭設置爲getForEntity方法的一部分,還是應該使用交換?我試圖設置oauth標頭作爲getForEntity調用的一部分。Resttemplate getForEntity - 傳遞標頭
是否可以將標頭設置爲getForEntity方法的一部分,還是應該使用交換?我試圖設置oauth標頭作爲getForEntity調用的一部分。Resttemplate 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());
}
}
你必須使用Exchange
。如果您查看文檔https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html,getForEntity不會將Object或HttpEntity作爲參數 – pvpkiran
謝謝@pvpkiran –