에몽이

HttpURLConnection 클래스 - URL 요청후 응답받기 ( GET방식, POST방식 ) [출처] [Java] HttpURLConnection 클래스 - URL 요청후 응답받기 ( GET방식, POST방식 )|작성자 자바킹 본문

java

HttpURLConnection 클래스 - URL 요청후 응답받기 ( GET방식, POST방식 ) [출처] [Java] HttpURLConnection 클래스 - URL 요청후 응답받기 ( GET방식, POST방식 )|작성자 자바킹

ian_hodge 2017. 1. 3. 19:45

참고] 관련 포스트 


http://javaking75.blog.me/140188363267



http://javaking75.blog.me/140210206646

 



[Java] HttpURLConnection 클래스 - URL 요청후 응답받기 ( GET, POST )


Java API Doc 

HttpURLConnection - http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html


 

 [코드] URLGetSample.java - GET 방식으로 요청 

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class URLGetSample {
    
    public static void main(String[] args) throws IOException {
        
        URL url = new URL("http://javaking75.blog.me/rss");
        
        // 문자열로 URL 표현
        System.out.println("URL :" + url.toExternalForm());
        
        // HTTP Connection 구하기 
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        
        // 요청 방식 설정 ( GET or POST or .. 별도로 설정하지않으면 GET 방식 )
        conn.setRequestMethod("GET"); 
        
        // 연결 타임아웃 설정 
        conn.setConnectTimeout(3000); // 3초 
        // 읽기 타임아웃 설정 
        conn.setReadTimeout(3000); // 3초 
        
        // 요청 방식 구하기
        System.out.println("getRequestMethod():" + conn.getRequestMethod());
        // 응답 콘텐츠 유형 구하기
        System.out.println("getContentType():" + conn.getContentType());
        // 응답 코드 구하기
        System.out.println("getResponseCode():"    + conn.getResponseCode());
        // 응답 메시지 구하기
        System.out.println("getResponseMessage():" + conn.getResponseMessage());
        
        
        // 응답 헤더의 정보를 모두 출력
        for (Map.Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
            for (String value : header.getValue()) {
                System.out.println(header.getKey() + " : " + value);
            }
        }
        
        // 응답 내용(BODY) 구하기        
        try (InputStream in = conn.getInputStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            
            byte[] buf = new byte[1024 * 8];
            int length = 0;
            while ((length = in.read(buf)) != -1) {
                out.write(buf, 0, length);
            }
            System.out.println(new String(out.toByteArray(), "UTF-8"));            
        }
        
        // 접속 해제
        conn.disconnect();
    }
}

 

> 콘솔에 출력된 결과 화면 (일부)


 

  


 

 [코드] URLPostSample.java - POST 방식으로 요청

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class URLPostSample {
    
    public static void main(String[] args) throws IOException {
        
        URL url = new URL("http://localhost:8080/test/SampleServlet");
        
        // HTTP 접속 구하기
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        
        // 리퀘스트 메소드를 POST로 설정
        conn.setRequestMethod("POST");
        
        // 연결된 connection 에서 출력도 하도록 설정 
        conn.setDoOutput(true);
    
        // 요청 파라미터 출력   
        // - 파라미터는 쿼리 문자열의 형식으로 지정 (ex) 이름=값&이름=값 형식&...
        // - 파라미터의 값으로 한국어 등을 송신하는 경우는 URL 인코딩을 해야 함.
        try (OutputStream out = conn.getOutputStream()) {
            out.write("id=javaking".getBytes());
            out.write("&".getBytes());
            out.write(("name=" + URLEncoder.encode("자바킹","UTF-8")).getBytes());
        }
                
        // 응답 내용(BODY) 구하기
        try (InputStream in = conn.getInputStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] buf = new byte[1024 * 8];
            int length = 0;
            while ((length = in.read(buf)) != -1) {
                out.write(buf, 0, length);
            }
            System.out.println(new String(out.toByteArray(), "UTF-8"));
        }
        // 접속 해제
        conn.disconnect();
    }    
}


> 결과  



[참고] 서버사이드 SampleServlet 코드 ( 자세한 내용은 첨부파일 참고 )


> SampleServlet 코드



 


> 요청시 서버 콘솔에 출력되는 내용 


Comments