Framework/SpringBoot
[Spring] Rest Template란?
hurlud
2023. 9. 9. 10:29
RestTemplate
RestTemplate는 스프링 프레임워크가 제공하는 클래스로, RESTful 웹 서비스와 상호작용 하는 과정을 단순화하여 편리하게 API를 호출할 수 있습니다.
RestTemplate의 동작 원리
- 어플리케이션이 RestTemplate를 생성합니다. (URI, HTTP 메서드 등 헤더를 담아서 요청함)
- RestTemplaterk HttpMessageConverter를 사용하여 requestEntity를 요청 메세지로 변환합니다.
- RestTemplate가 ClientHttpRequestFactory로 부터 ClientHttpRequest를 가져와서 요청을 보냅니다.
- ClientHttpRequest는 요청 메세지를 만들어 HTTP 프로토콜을 통해 서버와 통신합니다.
RestTemplate 메서드
메서드 | http | 설명 |
getForObject: Object | GET | GET 방식 요청으로 결과를 객체로 반환 |
getForEntity: ResponseEntity | GET | GET 방식 요청으로 결과를 ResponseEntity로 반환 |
postForLocation | POST | POST 방식 요청으로 결과를 헤더에 저장된 URI로 반환 |
postForLocation | POST | POST 방식 요청으로 결과를 객체로 반환 |
postForEntity : ResponseEntity | POST | POST 방식 요청으로 결과를 ResponseEntity로 반환 |
delete |
DELETE | DELETE 방식 요청으로 메서드 실행 |
put |
PUT | HTTP PUT 메서드를 실행 |
headForHeaders |
HEADER | 헤더의 정보를 얻을 수 있고, HTTP HEAD 메서드 사용 |
RestTemplate 의존성 추가
gradle
implementation 'org.apache.httpcomponents:httpcore:4.4.15'
implementation 'org.apache.httpcomponents:httpclient:4.5.13'
RestTemplate 사용 예제
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class RestApiClient {
public static void main(String[] args) {
// RestTemplate 인스턴스 생성
RestTemplate restTemplate = new RestTemplate();
// API 엔드포인트 URL 정의
String apiUrl = "https://api.example.com/data";
// GET 요청을 수행하고 응답을 ResponseEntity로 가져옴
ResponseEntity<String> response = restTemplate.getForEntity(apiUrl, String.class);
// 응답 데이터에 접근
String responseBody = response.getBody();
int statusCode = response.getStatusCodeValue();
System.out.println("상태 코드: " + statusCode);
System.out.println("응답 본문: " + responseBody);
}
}
reference
스프링 RestTemplate 정리(요청 함)
RestTemplate
velog.io
https://dejavuhyo.github.io/posts/spring-resttemplate/
Spring RestTemplate
1. RestTemplate이란 Spring에서 지원하는 객체로 간편하게 Rest 방식 API를 호출할 수 있는 Spring 내장 클래스이다. Spring 3.0부터 지원되었고, json, xml 응답을 모두 받을 수 있다.
dejavuhyo.github.io