Web & Server/Spring & Spring Boot

HttpURLConnection 을 이용한 HTTP 호출하기 (How to request HTTP url with HttpURLConnection)

Simplify - Jonghun 2019. 6. 5. 08:35

들어가며

Spring에서 Maven 으로 RestTemplate를 이용하지 않고 순수하게 Java에서의 Class를 이용해서 HTTP 호출하는 예제를 찾아 공유합니다.


구현방법

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



출처 : https://overcome26.tistory.com/77 http://nine01223.tistory.com/229