본문 바로가기

IT노트(구)/Java

자바 http url 호출 예제(HttpURLConnection 이용)

자바에서 HttpURLConnection은 대단히 자주 사용하는 클래스라고 할 수 있다!

다음은 가장 기본이 되는 호출 예제이다!<rest의 시대(?)를 살고 있는 개발자에게 필수가 아닐까?>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class Test01 {
    public static void main(String[] args) {
        BufferedReader in = null;
 
        try {
            URL obj = new URL("http://www.test.co.kr/test.jsp"); // 호출할 url
            HttpURLConnection con = (HttpURLConnection)obj.openConnection();
 
            con.setRequestMethod("GET");
 
            in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        
            String line;
            while((line = in.readLine()) != null) { // response를 차례대로 출력
                System.out.println(line);
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(in != nulltry { in.close(); } catch(Exception e) { e.printStackTrace(); }
        }
    }
}
cs