RestTemplate과 RequestEntity

song yuheon·2023년 9월 7일
0

Spring

목록 보기
63/93
post-thumbnail

RestTemplateRequestEntity는 Spring Framework에서 제공하는 클래스로, 웹 서비스와의 HTTP 통신을 돕는 역할을 한다. 이 클래스들을 사용하면 웹 서비스를 호출하거나 응답을 처리하는 작업을 간결하게 할 수 있다


RestTemplate


  • RestTemplate은 Spring에서 제공하는 HTTP 클라이언트 유틸리티 클래스이다. 이 클래스를 사용하면 RESTful 웹 서비스를 쉽게 호출할 수 있다.

    • HTTP 클라이언트 유틸리티 클래스
      프로그래밍에서 HTTP 방식으로 정보를 주고 받기 위해 사용하는 도구 혹은 기능을 모아 놓은 설계도(클래스)를 의미
    • RESTful 웹 서비스
  • 기본적인 HTTP 메서드(GET, POST, PUT, DELETE 등)를 지원한다.

  • 반환 타입에 따라 자동으로 응답을 직렬화하거나 역직렬화합니다. 예를 들어, JSON 응답을 Java 객체로 자동 변환해준다.

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject("http://example.com/api/resource", String.class);
    

RequestEntity


  • RequestEntity는 HTTP 요청을 표현하는 클래스디다. 요청 메서드, URL, 헤더 및 본문을 포함할 수 있다.

  • RequestEntity는 제네릭 타입을 가진다. 제네릭 타입은 HTTP 요청 본문의 타입을 나타냅니다.

  • 주로 RestTemplateexchange 메서드와 함께 사용되며 좀 더 복잡한 요청 정보(헤더 정보, HTTP 메서드 등)를 포함할 때 유용하다.

    URI uri = new URI("http://example.com/api/resource");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Custom-Header", "value");
    RequestEntity<String> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, uri);

두 클래스를 함께 사용하면, 다음과 같이 HTTP 요청을 보내고 응답을 받는 과정을 구현할 수 있다.

RestTemplate restTemplate = new RestTemplate();
URI uri = new URI("http://example.com/api/resource");
HttpHeaders headers = new HttpHeaders();
headers.set("Custom-Header", "value");
RequestEntity<String> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, uri);
ResponseEntity<String> response = restTemplate.exchange(requestEntity, String.class);

RequestEntity를 사용해 요청 정보를 정의하고 RestTemplateexchange 메서드를 통해 실제 요청을 보낸다. 그 후에 서버로부터의 응답은 ResponseEntity 객체에 담게 된다.


profile
backend_Devloper

0개의 댓글