[Spring] Rest Template란?

2023. 9. 9. 10:29·Framework/SpringBoot

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

https://velog.io/@soosungp33/%EC%8A%A4%ED%94%84%EB%A7%81-RestTemplate-%EC%A0%95%EB%A6%AC%EC%9A%94%EC%B2%AD-%ED%95%A8

 

스프링 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

 

'Framework > SpringBoot' 카테고리의 다른 글

[SpringBoot] created_at 처럼 엔티티 생성할 때 현재 날짜를 디폴트 값으로 지정하기 + 수정일 / Spring Data JPA automatic date creation  (0) 2023.12.24
[SpringBoot] 스프링 부트 data.sql이 실행되지 않을 때 (data.sql not working)  (0) 2023.12.24
[Spring] Spring에서 깃허브 OAuth 로그인하기  (0) 2023.09.01
[SpringBoot] @OneToMany, @ManyToOne, @ManyToMany 연관 관계 매핑, @JoinTable  (0) 2023.08.30
[SpringBoot]스프링 시큐리티란? (Spring Security)  (0) 2023.08.23
'Framework/SpringBoot' 카테고리의 다른 글
  • [SpringBoot] created_at 처럼 엔티티 생성할 때 현재 날짜를 디폴트 값으로 지정하기 + 수정일 / Spring Data JPA automatic date creation
  • [SpringBoot] 스프링 부트 data.sql이 실행되지 않을 때 (data.sql not working)
  • [Spring] Spring에서 깃허브 OAuth 로그인하기
  • [SpringBoot] @OneToMany, @ManyToOne, @ManyToMany 연관 관계 매핑, @JoinTable
hurlud
hurlud
나와 같은 궁금증을 가진 사람들을 위해 오늘도! 🐥
  • hurlud
    주독야독
    hurlud
  • 전체
    오늘
    어제
  • 최근 글

    • ALL (106)
      • CS (13)
      • Linux (2)
      • Deploy (7)
        • AWS (6)
        • Docker (1)
      • IDE (13)
        • IntelliJ (5)
        • Android Studio (8)
      • DB (10)
        • MySQL (6)
        • MongoDB (4)
      • Programming Language (20)
        • JavaScript (10)
        • Java (8)
        • Python (2)
      • Framework (32)
        • Node.js (6)
        • SpringBoot (17)
        • React (6)
        • NestJS (2)
      • Git | Github (4)
      • ETC (5)
      • Akka (0)
  • 링크

    • 깃허브
  • hELLO· Designed By정상우.v4.10.0
hurlud
[Spring] Rest Template란?
상단으로

티스토리툴바