Rest Client란?
: Rest API 서버에 HTTP 요청을 보낼 수 있는 클라이언트 툴 또는 라이브러리
ex) Postman (UI를 갖춘 Rest Client tool), RestTemplate (UI가 없는 Spring용 Rest Client API)
ex) RestTemplate을 이용해 적용할 수 있는 Java의 HTTP Client 라이브러리
: java.net.HttpURLConnection, Apache HttpComponents, OKHttp 3, Netty 등
용도
: 결제 대행 시스템을 이용할 수 있다
: 카카오톡 메세지 알림등을 사용할 수 있다
: 즉, server1에서 server2로 요청을 보내고 응답을 받는 형식 (외부 API 사용)
RestTemplate 객체 생성
1. RestClient 클래스에 RestTemplate 구현 객체를 생성.
이때, 생성자 파라미터로 Http Client 라이브러리의 구현객체를 전달.
HttpComponentsClientHttpRequestFactory 클래스를 통해 Apache HttpComponent를 전달.
Apache HttpComponent를 전달하기위해서 아래의 dependencies를 추가해야함
dependencies {
...
implementation 'org.apache.httpcomponents:httpclient'
}
2. HTTP Request를 전송할 Rest 엔드포인트의 URI 지정(생성)
UriComponentsBuilder 클래스를 통해 UriComponent객체를 생성
host의 worldtimeapi.org는 링크 참고 : http://worldtimeapi.org/
path의 {continents}와 {city}는 각각 uri객체생성 시, expand를 통해 {Asia}와 {Seoul}이 대입됨
3. 요청 전송 1 - getForObject() 메서드
restTemplate의 구현 메서드인 getForObject(URI uri, Class<T> responseType)을 통해 HTTP Request을 전송하여
서버의 리소스를 조회
4. 요청 전송 2 - getForObject() 를 이용한 커스텀 클래스 타입으로 원하는 정보만 응답으로 전달 받기
별도의 클래스를 지정해서 원하는 정보만 필터링. 이 클래스 타입의 객체로 getForObject에서 반환
이때, 응답 데이터의 JSON 프로퍼티 이름과, 클래스의 멤버변수이름이 동일해야함
또한, 헤당 멤버변수에 접근하기 위한 getter메서드더 동일한 이름이어야함
5. 요청 전송 3 - getForObject() 를 사용한 Response Body(바디, 컨텐츠) + Header(헤더) 정보 전달 받기
ResponseEntity클래스로 응답데이터를 래핑하여 전달되며, getBody(), getHeaders() 메서드 등을 이용해 정보를 얻음
getHeaders().entrySet() 은 응답으로 전달되는 모든 헤더 정보를 볼 수 있음
6. 요청 전송 4 - exchange를 사용한 응답 데이터 받기
HTTP Method, RequestEntity, ResponseEntity방식을 직접 지정해서 HTTP Request를 전송할 수 있는 일반적인 방식
1) URI uri : Request를 전송할 엔드포인트 URI 객체 지정
2) HttpMothod method : HTTP 메서드 타입 지정 (GET, POST, PATCH, DELETE 등)
3) HttpEntity<?> requestEntity : HttpEntity 개체를 통해 헤더, 바디, 파라미터 등을 설정
4) Class<T> responseType : 응답으로 전달받을 클래스의 타입을 지정
템플릿 코드
템플릿 REST Client코드
package SideProject.AnimalCenter.find.etc;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
public class RestClient {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
UriComponents uriComponents =
UriComponentsBuilder
.newInstance()
.scheme("http")
.host("worldtimeapi.org")
.port(80)
.path("/api/timezone/{continents}/{city}")
.encode()
.build();
URI uri = uriComponents.expand("Asia","Seoul").toUri();
String result = restTemplate.getForObject(uri, String.class);
WorldTime worldTime = restTemplate.getForObject(uri, WorldTime.class);
// ResponseEntity<WorldTime> response = restTemplate.getForEntity(uri, WorldTime.class);
ResponseEntity<WorldTime> response = restTemplate.exchange(uri, HttpMethod.GET, null, WorldTime.class);
System.out.println("# datatime: " + response.getBody().getDatetime());
System.out.println("# timezone: " + response.getBody().getTimezone());
System.out.println("day_of_week: " + response.getBody().getDay_of_week());
System.out.println("# HTTP status code: " + response.getStatusCode());
System.out.println("# HTTP Status Value: " + response.getStatusCodeValue());
System.out.println("# Content Type: " + response.getHeaders().getContentType());
System.out.println(response.getHeaders().entrySet());
}
}
템플릿 코드용 WorldTime Entity 클래스 코드
package SideProject.AnimalCenter.find.etc;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@AllArgsConstructor
@Setter
@Getter
public class WorldTime {
private String datetime;
private String timezone;
private int day_of_week;
public String getDatetime() {return datetime;}
public String getTimezone() {return timezone;}
public int getDay_of_week() {return day_of_week;}
}
외부 API 목록
공공 데이터 포털 : https://www.data.go.kr/dataset/3043385/openapi.do
카카오 REST API : https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api
네이버 API : https://developers.naver.com/products/intro/plan/plan.md
구글 API : https://console.cloud.google.com
공공 인공지능 API : https://aiopen.etri.re.kr/
'Java & Spring > 옵션정리' 카테고리의 다른 글
[Spring Boot] P6SPY 프레임 워크 - SQL 확장 (0) | 2022.10.23 |
---|---|
[Ngrok] 설치 및 실행 (0) | 2022.10.18 |
[리눅스] 프로세스 목록 보기 [ps] (0) | 2022.10.01 |
[JWT] JJWT (0) | 2022.09.26 |
[인증/보안] HTTP / HTTPS (0) | 2022.09.20 |