프로그램/Java

[Java] Rest API 연결 가이드 샘플

neorc 2025. 2. 26. 15:44

 

📌 Rest API 연결

  • Http, Https 프로토콜 타입별로 처리
  • HttpURLConnection 연결에 대해 가이드 샘플 구성

 

 


Rest Api Client

📌 예제 코드

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class RestApiClient {
    public static String sendHttpRequest(String targetUrl, String method, String jsonBody) {
        StringBuilder response = new StringBuilder();
        HttpURLConnection conn = null;
        OutputStream os = null;
        BufferedReader br = null;
        
        try {
            URL url = new URL(targetUrl);
            
            if (targetUrl.startsWith("https")) {
                conn = (HttpsURLConnection) url.openConnection();
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }
            
            conn.setRequestMethod(method);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            
            if (jsonBody != null && jsonBody.length() > 0) {
                os = conn.getOutputStream();
                os.write(jsonBody.getBytes("UTF-8"));
            }
            
            int responseCode = conn.getResponseCode();
            System.out.println("HTTP Response Code: " + responseCode);
            
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
        } catch (IOException e) {
            System.err.println("HTTP 요청 중 오류 발생: " + e.getMessage());
        } finally {
            try {
                if (os != null) os.close();
                if (br != null) br.close();
                if (conn != null) conn.disconnect();
            } catch (IOException e) {
                System.err.println("리소스 해제 중 오류 발생: " + e.getMessage());
            }
        }
        return response.toString();
    }

    public static void main(String[] args) {
        String url = "https://example.com/api";
        String method = "POST";
        String jsonBody = "{\"message\":\"Hello, API!\"}";

        String response = sendHttpRequest(url, method, jsonBody);
        System.out.println("Response: " + response);
    }
}

 

📌 출력 결과:

HTTP Response Code: 200
Response: {"status":"success","data":"Hello, Client!"}