728x90
반응형
RestTemplate
RestTemplate는 원래 스프링에서 HTTP 요청을 보낼 때 주로 사용되던 방법으로
동기식으로 작동하는 HTTP 클라이언트이다.
RestTemplate 객체를 생성하고 이 객체로 GET 요청과 POST 요청을 보낼 수 있다.
RestTemplate restTemplate = new RestTemplate();
GET 요청
String url = "https://random-data-api.com/api/v2/beers";
BeerGetDto response = restTemplate.getForObject(
url, BeerGetDto.class
);
log.info(response.toString());
getForObject()
응답의 Response Body가 어떤 타입인지를 명확히 알고 있고 다른 Stataus Code 등이 필요하지 않은 경우 활용 가능.
돌아온 응답을 두번째 인자로 지정한 객체로 해석하여 반환해준다.
POST 요청
String postBeerUrl = "http://localhost:8081/give-me-beer";
MessageDto responseDto = restTemplate.postForObject(
postBeerUrl,
requestBody,
MessageDto.class
);
log.info(responseDto.toString());
postForObject()
GET 요청과 유사한 형태로 작동한다.
GET과의 차이점이라 하면 GET은 request body 미포함, POST는 request body를 포함한다는 점.
Request Body를 DTO의 형태로 포함해 요청을 보낼 수 있다.
728x90
반응형