Skip to main content

RestfulAPI를 호출하기 위한 Class 및 Method 생성

  • RestfulAPI를 호출하기 위한 공통 클래스 및 메서드를 생성합니다.
  • 프로비저닝에서 PUT, DELETE는 쓰이지 않으므로, POST와 GET의 두가지 Method를 만듭니다.
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);
            }
        }
    }
}