[java] 자바 URL, HttpURLConnection 사용하기

자바에서 HTTP 요청을 보내는 방법을 알아보겠습니다. java.net.URLjava.net.HttpURLConnection 클래스를 사용하여 간단한 HTTP GET 및 POST 요청을 처리할 수 있습니다.

URL 클래스

java.net.URL 클래스는 URL 주소를 나타내는 객체를 만들기 위한 클래스입니다. 다음은 URL 클래스를 사용하여 URL을 만드는 예제입니다.

import java.net.URL;
import java.net.MalformedURLException;

public class URLExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://example.com/api/resource");
            // URL 객체를 사용하여 HTTP 연결을 수립하고 데이터를 송수신할 수 있음
        } catch (MalformedURLException e) {
            // URL이 잘못되었을 때 발생하는 예외 처리
            e.printStackTrace();
        }
    }
}

HttpURLConnection 클래스

java.net.HttpURLConnection 클래스는 HTTP 연결을 만들기 위한 클래스입니다. 이 클래스를 사용하여 웹 서버로부터 데이터를 읽거나 쓸 수 있습니다. 다음은 HttpURLConnection 클래스를 사용하여 GET 및 POST 요청을 보내는 예제입니다.

HTTP GET 요청 보내기

import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

public class HttpGetExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://example.com/api/resource");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            System.out.println(content);

            con.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

HTTP POST 요청 보내기

import java.net.URL;
import java.io.OutputStream;
import java.net.HttpURLConnection;

public class HttpPostExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://example.com/api/resource");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");

            con.setDoOutput(true);
            try (OutputStream out = con.getOutputStream()) {
                String requestBody = "param1=value1&param2=value2";
                out.write(requestBody.getBytes());
            }

            con.getInputStream();
            con.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

이제 여러분은 URL 및 HttpURLConnection 클래스를 사용하여 자바에서 간단한 HTTP 요청을 보내는 방법을 알게 되었습니다.

참고: Java 11을 기준으로 작성되었습니다.

Java HttpURLConnection Documentation