by Nathan

HTTP request 본문

Programming/JAVA

HTTP request

넷쓴 2017. 3. 20. 13:35




1. code


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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
 
 
public class Test {
 
    public static void main(String[] args) {
        System.out.println("\nOutput: \n" + callURL("http://localhost:8888/test"));
    }
 
    public static String callURL(String myURL) {
        System.out.println("Requeted URL:" + myURL);
        StringBuilder sb = new StringBuilder();
        URLConnection urlConn = null;
        InputStreamReader in = null;
        try {
            URL url = new URL(myURL);
            urlConn = url.openConnection();
            if (urlConn != null)
                urlConn.setReadTimeout(60 * 1000);
            if (urlConn != null && urlConn.getInputStream() != null) {
                in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
                BufferedReader bufferedReader = new BufferedReader(in); // 인풋스트림을 버퍼리더로 읽음
                if (bufferedReader != null) {
                    int cp;
                    while ((cp = bufferedReader.read()) != -1) {
                        sb.append((char) cp);
                    }
                    bufferedReader.close();
                }
            }
        in.close();
        } catch (Exception e) {
            throw new RuntimeException("Exception while calling URL:"+ myURL, e);
        } 
 
        return sb.toString();
    }
}
cs





2. result


1
2
3
4
5
6
7
8
9
10
11
12
13
14
Requested URL:http://crunchify.com/wp-content/uploads/code/json.sample.txt
 
Output: 
{"menu": {
  "id""file",
  "value""File",
  "popup": {
    "menuitem": [
      {"value""New""onclick""CreateNewDoc()"},
      {"value""Open""onclick""OpenDoc()"},
      {"value""Close""onclick""CloseDoc()"}
    ]
  }
}}
cs



'Programming > JAVA' 카테고리의 다른 글

엑셀 다운로드(gradle, poi3.7)  (0) 2018.07.30
엑셀 업로드(gradle, poi3.7)  (0) 2018.07.30
StringTokenizer  (0) 2017.03.17
Bubble sort  (0) 2017.03.17
request.getRemoteAddr() ipv4로 받기  (0) 2016.06.13
Comments