관리 메뉴

bright jazz music

RestTemplate 01 : 파라미터 없는 GET 요청 본문

Framework/Spring

RestTemplate 01 : 파라미터 없는 GET 요청

bright jazz music 2023. 3. 2. 15:49

 

 

RestTemplate (Spring Framework 6.0.5 API)

postForLocation Create a new resource by POSTing the given object to the URI template, and returns the value of the Location header. This header typically indicates where the new resource is stored. URI Template variables are expanded using the given URI v

docs.spring.io

 

1. RestTemplate이란

  • 스프링에서 HTTP 통신 기능을 간단히 사용하도록 설계된 템플릿이다.
  • 기본적으로 동기 방식으로 기능한다.
  • 비동기 방식을 사용하려면 AsyncRestTemplate을 사용하거나 WebClient를 사용해야 한다.

*RestTemplate은 spring-boot-starter-web 모듈에 포함돼 있으므로 별도의 의존성 추가가 필요 없다.

*AsyncRestTemplate는 deprecated 되었다. 스프링 5 이후부터는 WebClient를 사용을 권장한다.

 

 

2. RestTemplate의 특징

  • HTTP프로토콜의 메서드에 맞는 메서드 제공
  • RESTful 형식 구비
  • HTTP 요청 후 json, xml, 문자열 등의 형식으로 응답 수신 가능
  • 블로킹(blocking) I/O 기반의 "동기(synchronous)" 방식 사용
  • 다른 API 호출 시 HTTP 헤더에 값 추가 가능

 

3. RestTemplate 동작 과정

3.1 선언 및 객체 생성

애플리케이션에서 RestTemplate 을 선언하고 객체를 생성한다. 보통 이 작업은 서비스나 비즈니스 계층에서 진행된다. 또는 유틸리티 성격을 가진 별도의 클래스로 생성하기도 한다.

 

3.2 객체에 값 설정

생성된 객체에 URI, HTTP메서드, body, header 등을 설정한다.

 

3.3 외부 API에 요청 시작

외부 API에 요청을 보낸다. 이 과정에서 RestTemplate은 HttpMessageConverter를 사용하여 RequestEntity를 Request Message로 변환한다.

 

3.4  요청 가져온 후 발송하기

RestTemplate에서 변환된 요청 메시지를 ClientHttpRequestFactory를 통해 ClientHttpRequest로 가져온다. 가져온 후에는 외부 API로 요청을 보낸다.

 

3.5 응답 확인 

외부로부터 응답 수신하면 RestTemplate은 ResponseErrorHandler로 오류를 확인한다. 오류가 있다면 ClientHttpResponse에서 응답 데이터를 처리한다

 

3.6 응답이 정상인 경우

응답 데이터가 정상이라면 다시 HttpMessageConverter를 거쳐 자바 객체로 변환해서 애플리케이션으로 반환한다.

 

 

4. RestTemplate 구현

이번 포스팅에서는 일단 파라미터가 존재하지 않는 GET 요청을 테스트 한다.

 

1. 요청을 받아줄 서버(localhost:9090)를 만들고 테스트 할 컨트롤러를 작성한다.

2. 요청을 발송할 서버(8080)에 controller와 service를 만든다.

3. 요청 발송 서버의 service에 RestTemplate 객체를 생성하고 요청을 보낸다.

4. 요청 수신 서버가 요청 발송 서버로 응답을 보내면,  돌아오면 그것을 컨트롤러로 반환한다.

 

4.1 외부 api 역할을 할 서버 생성 (localhost:9090)

요청을 받아줄 외부 서버와 api를 만든다. 난 똑같은 프로젝트를 복사해서 포트만 변경해 준 뒤 사용하였다.

//외부 API 역할을 하는 서버 => server.port=9090
package com.project.base.controller;

import com.project.base.domain.MemberDto;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/crud-api")
public class CrudController {

    /* GET: 파라미터가 없는 경우 */
    @GetMapping
    public MemberDto getName() {
        //return "catnails from http://localhost:9090/api/v1/crud-api";
        //return MemberDto.builder().name("catnails").email("catnails@gmail.com").organization("catnails company").build();
        return new MemberDto("catnails", "catnails@gmail.com", "catnails company");
    }
}

http://localhost:9090/api/v1/crud-api"로 HTTP GET 요청을 받을 경우 MemberDTO 객체를 json 형식으로 반환한다.

 

 

//memberDto.java
package com.project.base.domain;

import lombok.Builder;
import lombok.Data;

//@Builder
@Data
public class MemberDto {

    public MemberDto(String name, String email, String organization){
        this.name =  name;
        this.email = email;
        this.organization = organization;
    }

    private String name;
    private String email;
    private String organization;

}

 

4.2 RestTemplateController 작성(localhost:8080)

요청 발송을 위한 서버 역할을 한다.

http://localhost:8080/rest-template 으로 접근하는 경우 restTemplateService.getName()을 호출한다.

//RestTemplateController.java
package com.project.base.controller;

import com.project.base.service.RestTemplateService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/rest-template")
//@RequiredArgsConstructor
public class RestTemplateController {

    private final RestTemplateService restTemplateService;

    public RestTemplateController(RestTemplateService restTemplateService) {
        this.restTemplateService = restTemplateService;
    }

    @GetMapping
    public String getName() {
        return restTemplateService.getName(); //서비스에 요청을 보내는 로직이 들어 있다.
    }
}

 

 

4.3 RestTemplateService 작성 (실제 RestTemplate을 선언하고 외부 API를 호출하는 계층)

이 계층에서 restTemplate을 선언하고 객체를 생성한다. 그리고 getForEntity메소드에 URI 정보와 응답을 받을 클래스를 파라미터로 넣어서 요청한다. 응답이 돌아올 때까지 스레드가 멈춰 있으며 응답이 돌아오는 경우 ResponseEntity에 담는다.

//RestTemplateService.java

package com.project.base.service;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

@Service
public class RestTemplateService {

    public String getName(){
        URI uri = UriComponentsBuilder
                .fromUriString("http://localhost:9090")
                .path("/api/v1/crud-api")
                .encode()
                .build()
                .toUri();

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);

        return responseEntity.getBody();
    }


}

 

과정 요약


localhost:8080

http://localhost:8080/rest-template 접근
=> RestTemaplateController.getName()
=> RestTemplateService.getName()
=> ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);

== http://localhost:9090//api/v1/crud-api 요청 발송 ==>


localhost:9090

=> CrudController.getName()
=> return new MemberDto("catnails", "catnails@gmail.com", "catnails company"); //객체 json 반환

<== 응답 발송 ==


=> ResponseEntity responseEntity = restTemplate.getForEntity(uri, String.class);
=> return responseEntity.getBody(); //RestTemplateController.getName()에 스트링 값 반환
=>RestTemplateController가 클라이언트(브라우저)에 string 값 반환

==================>> 

8080서버가 9090서버에서 발송한 json 응답의 내용을 클라이언트로 반환하였다.

 

*크롬 웹스토어에서 Json Formatter 또는 Json Viewer를 설치하여 사용하면 위처럼 json을 보기 쉽게 변환해 준다.

 

 

참고서적: 스프링 부트 핵심 가이드 - 장정우

 

https://product.kyobobook.co.kr/detail/S000061352140

 

스프링 부트 핵심 가이드 | 장정우 - 교보문고

스프링 부트 핵심 가이드 | 입문자의 눈높이에 맞춰 차근차근 따라 하면서 배우는 스프링 부트 입문서!《스프링 부트 핵심 가이드》는 스프링 부트 기반의 애플리케이션을 개발할 때 필요한 기

product.kyobobook.co.kr

 

 

Comments