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

1. 시작하며

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();

Revision #2
Created 10 October 2023 22:38:28 by Johnny Kim
Updated 15 October 2023 14:49:03 by Johnny Kim