본문 바로가기
개발자 로그

HttpURLConnection API 만들기

by Hello_World_! 2025. 7. 18.
반응형

 

📡 Java에서 HttpURLConnection으로 API 호출하기 (GET & POST 방식)

1. 개요

Java에서 외부 API 서버와 통신할 때 사용하는 대표적인 클래스 중 하나가 HttpURLConnection입니다.
Spring Boot가 아닌 레거시 프로젝트(예: JSP, 서블릿, 구형 Spring MVC 등)에서는 여전히 이 방식을 널리 사용합니다.
REST API 호출을 통해 데이터를 가져오거나 서버에 전송하는 구조에서 필수적인 방식입니다.

2. HttpURLConnection vs HttpClient 차이

Java 11부터는 새로운 방식인 HttpClient가 등장하였지만, 아직 많은 실무 프로젝트에서 HttpURLConnection이 사용되고 있습니다.
아래는 두 방식의 차이를 비교한 표입니다.

구분 HttpURLConnection HttpClient (Java 11+)
지원 버전 Java 1.1부터 지원 Java 11 이상
사용 방식 절차지향, 복잡한 설정 필요 비동기 지원, 함수형 스타일
응답 처리 InputStream 수동 처리 BodyHandler 사용 가능
추천 사용 환경 레거시 시스템, 서블릿 기반 모던 웹 애플리케이션, Java 11+

3. GET 방식 API 호출 예제

GET 방식은 데이터를 조회할 때 사용합니다. URL에 파라미터를 포함해 요청을 전달하며, 서버에서 데이터를 받아옵니다.


public static String sendGet(String apiUrl) throws IOException {
    StringBuilder result = new StringBuilder();
    URL url = new URL(apiUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);

    int responseCode = conn.getResponseCode();
    if (responseCode == 200) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                result.append(line);
            }
        }
    } else {
        System.out.println("GET 요청 실패. 응답 코드: " + responseCode);
    }

    return result.toString();
}

// 사용 예시
public static void main(String[] args) throws Exception {
    String apiUrl = "https://jsonplaceholder.typicode.com/posts/1";
    String response = sendGet(apiUrl);
    System.out.println("응답 결과: " + response);
}

4. POST 방식 API 호출 예제

POST 방식은 서버에 데이터를 등록하거나 수정할 때 사용합니다. JSON 또는 Form 데이터를 Request Body에 포함시켜 전송합니다.


public static String sendPost(String apiUrl, String jsonData) throws IOException {
    StringBuilder result = new StringBuilder();
    URL url = new URL(apiUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json; utf-8");
    conn.setDoOutput(true);

    try (OutputStream os = conn.getOutputStream()) {
        byte[] input = jsonData.getBytes("utf-8");
        os.write(input, 0, input.length);
    }

    int responseCode = conn.getResponseCode();
    if (responseCode == 200 || responseCode == 201) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
            String line;
            while ((line = br.readLine()) != null) {
                result.append(line.trim());
            }
        }
    } else {
        System.out.println("POST 요청 실패. 응답 코드: " + responseCode);
    }

    return result.toString();
}

// 사용 예시
public static void main(String[] args) throws Exception {
    String apiUrl = "https://jsonplaceholder.typicode.com/posts";
    String jsonInput = "{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }";

    String response = sendPost(apiUrl, jsonInput);
    System.out.println("응답 결과: " + response);
}

5. 마무리 정리

  • HttpURLConnection은 레거시 시스템에 적합한 API 통신 방식입니다.
  • GET은 조회, POST는 생성/수정 등 목적에 따라 적절히 사용해야 합니다.
  • 응답 코드는 반드시 확인하고, 예외 처리를 철저히 해야 합니다.
  • 향후 유지보수를 고려한다면 Java 11 이상에서는 HttpClient로의 전환도 고려해야 합니다.

✔️ 위 코드는 Java 8에서도 동작하며, Spring 없이도 API 통신 기능을 구현할 수 있습니다.