Pages

2014년 10월 30일 목요일

[JAVA] HTTPS Request 예제


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
62
63
64
65
66
67
68
69
public class HttpsRequestExample {
    private final String USER_AGENT = "Mozilla/5.0";
 
    public boolean requestData(JSONObject jsonVal) throws Exception {
        boolean rtnBool = false;
        String url = "https://127.0.0.1:8089/restful/users";
 
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        
        /************************ 인증서 적용 후 제거 할 것 START **********************/
        con.setHostnameVerifier(new HostnameVerifier() {        
            public boolean verify(String hostname, SSLSession session)  {  
            return true;
            }
        });
        /************************ 인증서  적용 후 제거 할 것 END **********************/
        
        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Content-Type""application/json");
        con.setRequestProperty("Accept-Language""en-US,en;q=0.5");
 
        Gson g = new Gson();
        String json = g.toJson(jsonVal);
         
        System.out.println(json);
        
        con.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
        out.write(json.toString());
        out.close();
 
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + json);
        System.out.println("Response Code : " + responseCode);
        
        if(responseCode != 200){
            System.out.println("연결 실패");
        }
 
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
 
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
 
        //response 값은 "{code:200, Agent:{ID:12398723418974}}" 형식
 
        JSONObject jResponse = JSONObject.fromObject(response.toString());
        String code = jResponse.get("code").toString();
 
        JSONObject jAgent = JSONObject.fromObject(jResponse.get("Agent").toString());
        String ids = jAgent.get("ID").toString();
 
        if("200".equals(code) && !"".equals(ids)){
            rtnBool = true;
        }else{
            System.out.println("RESPONSE CODE : " + code + " , ID : " + ids);
        }
 
        return rtnBool;
    }
}

댓글 없음:

댓글 쓰기