2017-05-10 1 views
1

getForEntity 메소드의 일부로 헤더를 설정할 수 있습니까? 아니면 exchange를 사용해야합니까? getForEntity 호출의 일부로 oauth 헤더를 설정하려고합니다.Resttemplate getForEntity - 전달 헤더

+3

합니다. docs https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html을 보면 getForEntity는 Object 또는 HttpEntity를 인수로 취하지 않습니다. – pvpkiran

+0

감사합니다. @pvpkiran –

답변

1

당신은 .exchange를 사용할 수 있습니다

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

전체의 JUnit 샘플 : Exchange를 사용할 필요가

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

}