JSP/SERVLET
2018.03.31 / 16:23

[JAVA]HttpClient Https 서버 연동

봄이
추천 수 39

Colored By Color Scripter

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.X509Certificate;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HttpsTest {



//        public static void main(String[] args) throws Exception {
    @RequestMapping("/tachyontest.do")
    public void test() throws NoSuchAlgorithmException, KeyManagementException, ClientProtocolException, IOException{
            HttpClient httpclient = new DefaultHttpClient();

            TrustManager easyTrustManager = new X509TrustManager() {
                
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    // TODO Auto-generated method stub
                    return null;
                }
                
                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain,
                        String authType) throws CertificateException {
                    // TODO Auto-generated method stub
                    
                }
                
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain,
                        String authType) throws CertificateException {
                    // TODO Auto-generated method stub
                    
                }
            };
            
            //. HttpClient의 경우 X509TrustManager를 이용해 SSLContext를 생성하고
            //ClientConnectionManager와 SchemeRegistry에 SSLSocketFactory를 등록해 준다.
            
            try {
                SSLContext sslcontext = SSLContext.getInstance("TLS");//SSLContext 지정된 시큐어 소켓 프로토콜 구현
                sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);

                SSLSocketFactory socketFactory = new SSLSocketFactory(sslcontext,SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

//                SSLSocketFactory socketFactory = new SSLSocketFactory(sslcontext,
//                        SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
//                만약 본인 인증 방식 (Self-Signed Certificate)일 경우는 “SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER”선언된 코드를
//                주석해제 하시면 됩니다. 물론 바로 위의 ” SSLSocketFactory.STRICT_HOSTNAME_VERIFIER”코드는 주석 처리
                
                Scheme sch = new Scheme("https", 443, socketFactory);//SSL기본포트 : 443
                httpclient.getConnectionManager().getSchemeRegistry().register(sch);

                
//                HttpGet httpget = new HttpGet("https://msp.f-secure.com/web-test/common/test.html");
//                System.out.println("executing request" + httpget.getRequestLine());
//                HttpResponse response = httpclient.execute(httpget);

                //HttpClient timeout 셋팅
                httpclient.getParams().setParameter("http.protocol.expect-continue", false);//HttpClient POST 요청시 Expect 헤더정보 사용 x
                httpclient.getParams().setParameter("http.connection.timeout", 3 * 1000);// 원격 호스트와 연결을 설정하는 시간
                httpclient.getParams().setParameter("http.socket.timeout",  3 * 1000);//데이터를 기다리는 시간
                httpclient.getParams().setParameter("http.connection-manager.timeout",  3 * 1000);// 연결 및 소켓 시간 초과 
                httpclient.getParams().setParameter("http.protocol.head-body-timeout",  3 * 1000);
                
                String url = "해당서버 url"; //server url (https로 되어있는)
                
                HttpPost httppost = new HttpPost(url);                
                System.out.println("executing request" + httppost.getRequestLine());                
                

                String sampleJson =
                        "[" +
                                "{" +
                                    "\"filesize\": \"1398259\"," +
                                    "\"crc32_1\": \"0x00001226\"," +
                                    "\"crc32_2\": \"0x2A49AB1A\"," +
                                    "\"crc32_3\": \"0x3B642DBE\"," +
                                    "\"crc32_4\": \"0x00000C91\"," +
                                    "\"ukey\": \"053F\"" +
                                "}," +
                                "{" +
                                    "\"filesize\": \"880114\"," +
                                    "\"crc32_1\": \"0x0000144C\"," +
                                    "\"crc32_2\": \"0x67D8725E\"," +
                                    "\"crc32_3\": \"0xE212B08C\"," +
                                    "\"crc32_4\": \"0x00005F5C\"," +
                                    "\"ukey\": \"407F\"" +
                                "}" +
                        "]"; 
                
                        
                

                
                 List<NameValuePair> qparams = new ArrayList<NameValuePair>();         
                 qparams.add(new BasicNameValuePair("json",sampleJson));
                
                UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(qparams,"UTF-8");
                httppost.setEntity(entity1);
                
                HttpResponse response = httpclient.execute(httppost);

                HttpEntity entity = response.getEntity();

                String responseBody = EntityUtils.toString(response.getEntity(),"UTF-8");

                System.out.println(responseBody);

                System.out.println("————————————————————");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: "+ entity.getContentLength());
                }
                EntityUtils.consume(entity);

            } finally {
               //Apache의 HttpClient 라이버러리에서는 웹 서버를 연결을 하고 난후 명시적으로 끊는 부분이 없을 경우 대기 상태로 넘어가며,
             //이런 대기가 여러개 발생하게 되면 웹서버의 네트워크 리소스에 누수가 발생할 수가 있다. 
             httpclient.getConnectionManager().shutdown();//<-httpclient의 접속 끊기. 
            }
            

        }
    

}

 

 

  • 기존의 httpclient의  post 방식이나 get 방식의 코드에서 노란색 블록부분을 추가하면된다.