Java REST API 호출하기

NameJM·2024년 7월 22일

Spring boot 2.7.10, jdk 1.8

implementation 'org.json:json:20230227'

public JSONObject callApi(String obj, String urlParam) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
	return callApi(obj, urlParam, "POST");
}
    
public JSONObject callApi(String obj, String urlParam, String method) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
	HttpURLConnection conn = null;
    JSONObject responseJson = null;

    URL url = new URL(urlParam);

    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(method);
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("cache-control", "no-cache");
    conn.setRequestProperty("pragma", "no-cache");
    conn.setDoOutput(true);

    if(obj != null) {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));

        try {
            bw.write(obj);
            bw.flush();
            bw.close();
        } catch (IOException e) {
            log.error("Error : {}", e.getMessage());
        } finally {
            if (bw != null) {
                bw.close();
            }
        }
    }

    int responseCode = conn.getResponseCode();
    BufferedReader br;
    StringBuilder sb = new StringBuilder();
    if (100 <= responseCode && responseCode <= 399) {
        br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    } else{
        br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
    }
    String line = "";
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    try {
        br.close();
    }catch (IOException e){
        log.error("Error : {}", e.getMessage());
    }finally {
        br.close();
    }
    responseJson = new JSONObject(sb.toString());
    log.info("responseJson :: {}", responseJson);

    return responseJson;
}

0개의 댓글