RestTemplate으로 외부 API 호출하기RestTemplate은 Spring Framework에서 제공하는 HTTP 통신 클라이언트입니다.
외부 REST API와 통신할 때 간단하게 사용할 수 있으며, JSON 데이터 전송/수신에 특히 유용합니다.
GET, POST, PUT, DELETE 요청에 사용됨String, Map, 또는 DTO 객체로 쉽게 매핑 가능import org.springframework.web.client.RestTemplate;
public class RestTemplateGetExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = /* 요청하고자 하는 url 주소 */;
String response = restTemplate.getForObject(url, String.class);
System.out.println("GET 응답 결과:");
System.out.println(response);
}
}
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
public class RestTemplatePostExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = /* 요청하고자 하는 url 주소 */;
// JSON 전송을 위한 데이터 구성
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("title", "foo");
requestBody.put("body", "bar");
requestBody.put("userId", 1);
// 헤더 설정
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// HttpEntity에 헤더와 바디 담기
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
// POST 요청 보내기
String response = restTemplate.postForObject(url, entity, String.class);
System.out.println("POST 응답 결과:");
System.out.println(response);
}
}
| 항목 | RestTemplate | WebClient |
|---|---|---|
| 방식 | 동기 (Blocking) | 비동기 (Non-blocking, Reactive) |
| 사용성 | 간단하고 익숙함 | 복잡하지만 유연함 |
| 권장 여부 | Spring 5 이하에서 유용 | Spring 5 이상에서 권장됨 |
RestTemplate은 간단한 HTTP 요청에 적합하며, 동기 방식으로 작동합니다.WebClient 사용이 권장되지만, 레거시 시스템이나 단순 호출에는 여전히 유용합니다.