본문 바로가기
개발/Spring

[Spring] RestTemplate 사용하기

by devhooney 2022. 10. 31.
728x90

RestTemplate은 스프링 프레임워크에서 제공하는 간단하고 동기화된 REST 클라이언트이다.

 

용도는 서버에서 다른 서버의 API를 호출할 때 사용된다.

 

주요 사용되는 메소드의 기능이다. 외울 필요는 없고, 그때 그때 찾아보는게 효율적일듯

 

메소드 기능
delete() 지정된 URL의 리소스에 http delete 요청 수행
exchange() 지정된 http 메소드를 url에 대해 실행. response body와 연결되는 객체를 포함하는 responseEntity를 리턴
execute() 지정된 http메소드를 url에 대해 실행. response body와 연결되는 객체를 리턴
getForEntity() http get request 전송. response body와 연결되는 객체를 포함하는 responseEntity 리턴
getForObject() http get request 전송. response body와 연결되는 객체 리턴
headForHeaders() http header request 전송. 지정된 리소스의 url의 http 헤더 리턴
optionsForAllow() http options request 전송. 지정된 url의 allow 헤더를 리턴
patchForObject() http patch request 전송. response body와 연결되는 결과 객체를 리턴
postForEntity() http post request 전송. response body와 연결되는 객체를 포함하는 responseEntity 리턴
postForLocation() http post request 전송. 새로 생성된 리소스의 url 리턴
postForObject() http post request 전송. response body와 연결되는 결과 객체를 리턴
put() 리소스 데이터를 지정된 url에 put

 

위 메소드들은 

  • 가변 인자 리스트에 지정된 URL 매개변수에 URL 문자열(String)을 인자로 받는다.
  • Map<String, String>에 지정된 URL 매개변수에 URL 문자열을 인자로 받는다.
  • Java.net.URI를 URL에 대한 인자로 받으며, 매개변수화된 URL은 지원하지 않는다.

 

사용 방법

RestTemplate rest = new RestTemplate();

// 빈으로 선언
@Bean
public RestTemplate restTemplate() {
	return new RestTemplate();
}

 

- GET

// getForObject
public User getUserById(String userId) {
    return rest.getForObject(
    	"http://localhost:8080/user/{id}",
    	User.class,
        userId
    );
}


// Map
// {id}가 Map의 id로 교체된다.
public User getUserById(String userId) {
    Map<String, String> urlVar = new HashMap<>();
    urlVar.put("id", userId);
    return rest.getForObject(
    	"http://localhost:8080/user/{id}",
    	User.class,
        urlVar
    );
}


// URI 매개변수 사용시
public User getUserById(String userId) {
    Map<String, String> urlVar = new HashMap<>();
    urlVar.put("id", userId);
    URI url = UriComponentsBuilder()
    	.fromHttpUrl("http://localhost:8080/user/{id}")
        .build(urlVar);
    return rest.getForObject(
    	url,
        User.class
    );
}

 

3개의 메소드 전부 ResposeEntity 객체를 리턴받는다.

 

 

- PUT

public void updateUser(User user) {
    rest.put("http://localhost:8080/user/{id}",
            user,
            user.getId()
    );
}

 

put() 메소드는 객체 자체를 전송하고 리턴값은 없다.

 

 

- DELETE

public void deleteUser(User user) {
    rest.delete(
    	"http://localhost:8080/user/{id}",
        user.getId();
    );
}

 

delete() 메소드는 객체는 필요 없고 ID만 넘겨주면 된다. 리턴값은 없다.

 

 

- POST

public User createUser(User user) {
    return rest.postForObject(
        "http://localhost:8080/user",
        user,
        user.class
    );
}


// 리소스의 위치가 필요할 경우
// 리소스의 URI를 반환한다.
public User createUser(User user) {
    return rest.postForLocation(
        "http://localhost:8080/user",
        user
    );
}


// 리소스의 위치와 객체가 들 다 필요할 경우
public User createUser(User user) {
    ResponseEntity<User> responseEntity = 
        rest.postForEntity(
            "http://localhost:8080/user",
            user,
            user.class
        );
    System.out.println(responseEntity.getHeaders().getLocation());
    return response.getBody();
}

 

 

- 참조

Spring in Action 제 5판

728x90