RestfulAPI를 호출하기 위한 Class 및 Method 생성
1. 시작하며
RestfulAPI를반복되는 호출하기작업의 편의성을 위한해 공통 클래스 및 메서드를 생성합니다.
- 프로비저닝에서 PUT, DELETE는 쓰이지 않으므로, POST와 GET의 두가지 Method를 만듭니다.
- Token관련 부분은 토큰 저장 챕터를 확인하여 주시기 바랍니다.
- 각 클래스에서 궁금한 내용은 Swit CTS의 깃허브를 참조해 주시기 바랍니다.
2. 예제 코드
package io.swit.api.util;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.swit.api.config.Variables;
import io.swit.api.model.dto.eai.SwitTokenDto;
import io.swit.api.service.com.LogService;
import io.swit.api.service.eai.AuthService;
import lombok.AllArgsConstructor;
import org.json.simple.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import java.time.LocalDateTime;
@Component
@AllArgsConstructor
public class HttpUtils{
private Variables var;
private AuthService authService;
private LogService logService;
/**
* POST 호출을 위한 Method
* @param apiUrl 호출 URL
* @param params 파라미터
* @param tokenDto 토큰 정보
* @return
* @throws Exception
*/
public JsonObject post(String apiUrl, JSONObject params, SwitTokenDto tokenDto) throws Exception {
try{
// API 호출을 위해 WebClient 설정
WebClient webClient = WebClient.builder()
.baseUrl(String.format("%s/v1/api/%s", var.API_URL, apiUrl))
.defaultHeaders(httpHeaders -> {
httpHeaders.set("Accept", "application/json");
httpHeaders.set(
"Authorization",
String.format("Bearer %s", tokenDto.getAccessToken().replace("\"", ""))
);
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
})
.build();
// API 호출 및 결과 수신
String retVal = webClient.post()
.bodyValue(params)
.retrieve()
.bodyToMono(String.class)
.block();
// 수신된 결과를 JSON Object로 변환
JsonParser parser = new JsonParser();
JsonObject jsonObject = new JsonObject();
if(retVal != null) {
Object obj = parser.parse(retVal);
jsonObject = (JsonObject) obj;
}
return jsonObject;
}catch (Exception e){
if(e.getMessage().contains("Unauthorized")){
return this.post(apiUrl,params,authService.getRefreshToken());
}else{
logService.saveErrorLog(e, "[POST]"+apiUrl);
throw new Exception(e);
}
}
}
/**
* Get Method
* @param apiUrl API 주소
* @param tokenDto 토큰 정보
* @return
* @throws Exception
*/
public JsonObject get(String apiUrl, SwitTokenDto tokenDto) throws Exception {
try{
// 전송을 위해 WebClient 설정
WebClient webClient = WebClient.builder()
.baseUrl(String.format("%s/v1/api/%s", var.API_URL, apiUrl))
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.build();
// API 호출 및 결과 수신
String retVal = webClient.get()
.headers(
httpHeaders -> {
httpHeaders.set("Accept", "application/json");
httpHeaders.set(
"Authorization",
String.format("Bearer %s", tokenDto.getAccessToken().replace("\"", ""))
);
}
)
.retrieve()
.bodyToMono(String.class)
.block();
// 수신한 결과를 JSON Object로 변환
JsonParser parser = new JsonParser();
Object obj = parser.parse(retVal);
JsonObject jsonObject = (JsonObject)obj;
return jsonObject;
}catch (Exception e){
if(e.getMessage().contains("Unauthorized")){
return this.get(apiUrl,authService.getRefreshToken());
}else{
logService.saveErrorLog(e, "[GET]"+apiUrl);
throw new Exception(e);
}
}
}
}
3. 코드 설명
// API 호출을 위해 WebClient 설정
WebClient webClient = WebClient.builder()
.baseUrl(String.format("%s/v1/api/%s", var.API_URL, apiUrl))
.defaultHeaders(httpHeaders -> {
httpHeaders.set("Accept", "application/json");
httpHeaders.set("Authorization", String.format("Bearer %s", tokenDto.getAccessToken().replace("\"", "")));
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
})
.build();
- Webflux의 WebClient를 이용하기 위해 호출할 URL과 인증 정보를 설정해 줍니다.
- 헤더에 Bearer 토큰으로 저장한 Access Token을 삽입하고, 매체유형은 JSON으로 설정해 줍니다.