1. RestTemplate 사용 이유
RestTemplate은 Spring Framework에서 제공하는 HTTP 통신을 간편하게 처리할 수 있는 클래스입니다. org.springframework.web.client.RestTemplate 패키지에 존재 합니다.
RESTful 웹 서비스와의 통신을 위해 주로 사용되고 기본적으로 동기 방식으로 처리되며, 비동기 방식으로 처리하고 싶을 경우 AsyncRestTemplate를 사용하면 됩니다.
JSONPlaceholder - Free Fake REST API
{JSON} Placeholder Free fake and reliable API for testing and prototyping. Powered by JSON Server + LowDB. Serving ~3 billion requests each month.
jsonplaceholder.typicode.com
RestTemplate 대표적 메서드
RestTemplate Method | HTTP Method | 설명 |
getForEntity | GET | get 요청을 보내고 ResponseEntity로 응답을 받음 |
getForObject | GET | get 요청을 보내고 java object로 매핑받아서 반환받음 |
exchange | Any | 헤더 세팅해서 HTTP Method로 요청보내고 ResponseEntity로 반환받음 |
put | PUT | PUT 형식으로 요청 |
delete | DELETE | DELETE 형식으로 요청 |
postForLocation | POST | post 요청을 보내고 java.net.URI 로 반환받음 |
postForObject | POST | post 요청을 보내고 Object로 반환받음 |
postForEntity | POST | POST 방식으로 요청하면 ResponseEntity를 반환해 준다. |
optionsForAllow | OPTIONS | 해당 URI에서 지원하는 HTTP 메서드를 조회 |
execute | Any | 요청과 응답에 대한 콜백 수정 |
2. 코드
package com.tenco.bank.controller;
import java.net.URI;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import com.tenco.bank.dto.Post;
import com.tenco.bank.dto.Todo;
// @Controller + @ResponseBody
@RestController // IoC 대상
public class HomeController {
// 주소설계 : http://localhost:8080/m-todos/${id}
// 테스트 주소 : http://localhost:8080/m-todos/10
@GetMapping("/m-todos/{id}")
public ResponseEntity<?> resetTest1(@PathVariable(name ="id") Integer id) {
// 1. 데이터 추출 확인
System.out.println("id : " + id);
// RestTemplate 사용법
// 1. URL 객체를 설정한다.
URI uri = UriComponentsBuilder
.fromUriString("https://jsonplaceholder.typicode.com/")
.path("/todos")
.path("/" + id)
.build()
.toUri();
// 2.
RestTemplate restTemplate1 = new RestTemplate();
ResponseEntity<Todo> response = restTemplate1.getForEntity(uri, Todo.class);
System.out.println(response.getStatusCode());
System.out.println("---------------------------");
System.out.println(response.getHeaders());
System.out.println("---------------------------");
System.out.println(response.getBody());
return ResponseEntity.status(HttpStatus.OK).body(response.getBody());
}
// 주소설계 : http://localhost:8080/exchange-test
@GetMapping("/exchange-test")
public ResponseEntity<?> restChangeTest() {
// 여기 주소는 리소스 서버 주소 설정을 해야 한다.
URI uri = UriComponentsBuilder
.fromUriString("https://jsonplaceholder.typicode.com/")
.path("/posts")
.build()
.toUri();
// 2. 객체 생성
RestTemplate restTemplate1 = new RestTemplate();
// exchange 메서드 활용
// 1. 헤더 구성
HttpHeaders headers = new HttpHeaders();
// 'Content-type': 'application/json; charset=UTF-8'
headers.add("Content-type", "application/json; charset=UTF-8");
// 2. 바디 구성
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("title", "안녕 반가워");
params.add("body", "후미진 어느 언덕에서 도시락 먹기");
params.add("userId", "11");
// 3. 헤더와 바디 결함
HttpEntity<MultiValueMap<String, String>> requestEntity
= new HttpEntity<>(params, headers);
// 4. RestTemplate 을 활용해서 HTTP 통신 요청
ResponseEntity<Post> response = restTemplate1.exchange(uri, HttpMethod.POST, requestEntity, Post.class);
System.out.println("response Header : " + response.getHeaders());
System.out.println("response body : " + response.getBody());
return ResponseEntity.status(HttpStatus.CREATED).body(response.getBody());
}
}
'Spring Boot > 추가 개념' 카테고리의 다른 글
OOP 회원과 주문 관리 설계 (2) | 2024.10.01 |
---|---|
API 설계 및 모범 사례 (1) | 2024.09.27 |
스프링부트 블로그 만들기 테스트 (0) | 2024.08.19 |
Bank 카카오 소셜로그인 처리 (1) | 2024.08.19 |
OAuth 2.0 이란 (Open Authorization) (0) | 2024.08.19 |