백엔드

[Spring] RestTemplate이란?

콩지연 2023. 8. 15. 22:05

- RestTemplate이란?

Spring에서 지원하는 객체로 간편하게 Rest방식으로 API를 호출할 수 있는 Spring 내장 클래스다.Spring 3.0부터 지원되었고, json과 xml 응답 모두 받을 수 있다.

 

Rest API 서비스를 요청 후 응답받을 수 있도록 설계되어 있으며,

HTTP 프로토콜의 메서드(GET, POST, DELETE, PUT)들에 적합한 여러 메서드를을 제공한다.

그래서 JAVA에서 사용되는 다른 템플릿처럼 단순 메서드 호출만으로 작업을 쉽게 처리할 수 있다!

 

 

- RestTemplate의 특징

1. Spring 3.0부터 지원하는 Spring의 HTTP 통신 템플릿

2. HTTP 요청 후 JSON, XML, String과 같은 응답을 받을 수 있는 템플릿

3. Blocking I/O 기반의 동기 방식을 사용하는 템플릿

4. RESTful 형식에 맞추어진 템플릿

5. Header, Content-Type등을 설정하여 외부 API 호출

6. Server to Server 통신에 사용

 

 

- RestTemplate의 흐름(아키텍쳐)

스프링에서 RestTemplate을 이용해 API를 호출할 때 동작 흐름 그림이다!

1 어플리케이션에서 RestTemplate의 메서드를 이용해 REST API 호출을 의뢰한다.
2 RestTemplate은 HttpMessageConverter를 이용해 어플리케이션에서 전송한 자바 객체를 메세지 형태로 변환한다.
3 RestTemplate은 ClientHttpRequestFactory에서 가져온 ClientHttpReqeust에게 메세지 전송을 의뢰한다.
4 ClientHttpReqeust는 요청 메세지를 작성 후 HTTP 통신 프로토콜로 REST API 서버와 통신한다.
5 RestTemplate은 ResponseErrorHandler를 통해 오류발생여부를 확인한다.
6 ResponseErrorHandler는 ClientHttpResponse의 응답 데이터를 가져와 오류를 처리한다.
7 RestTemplate은 HttpMessageConverter를 이용해 응답 메세지를 자바 객체로 변환한다.
8 RestTemplate은 REST API 호출 결과를 어플리케이션에 반환한다.

 

- RestTemplate의 메서드

 

- RestTemplate (PostForObject) 사용해보기

1. 의존성 추가

maven

<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpcore</artifactId>
   <version>4.4.15</version>
</dependency>

<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.13</version>
</dependency>

 

gradle

implementation 'org.apache.httpcomponents:httpcore:4.4.15'
implementation 'org.apache.httpcomponents:httpclient:4.5.13'

 

 

2. 헤더값 코드 작성하기

private HttpHeaders getHeaders() {
    HttpHeaders httpHeaders = new HttpHeaders();

    String auth = "헤더 값을 작성해주세요!";
    String contentType = "application/x-www-form-urlencoded;charset=utf-8";

    httpHeaders.add("Authorization", auth);
    httpHeaders.add("Content-type", contentType);

    return httpHeaders;
}

 

 

3. RestTemplate 코드 작성해보기

public Response useRestTemplate(){

    MultiValueMap<String, String> parameterValue = new LinkedMultiValueMap<>();
    parameterValue.add("본문 값 이름", "본문 값");
    parameterValue.add("본문 값 이름", "본문 값");

    //HttpEntity에 본문 값인 parameterValue와 헤더를 넣기
    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(parameterValue, this.getHeaders());

    //restTemplate
    RestTemplate restTemplate = new RestTemplate();

    KakaoCancelResponse cancelResponse = restTemplate.postForObject(
            "https://................",				//요청을 보낼 url
            requestEntity,					//본문 값
            Response.class					//응답받을 클래스
    );

    return Response;
}