k94314517
2024-05-21 6a394fff5528c02f981abc0e9ee2d7211b694b70
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package cn.emay.sdk.util.http.client;
 
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import cn.emay.sdk.util.http.common.EmayHttpResultCode;
import cn.emay.sdk.util.http.request.EmayHttpRequest;
import cn.emay.sdk.util.http.response.EmayHttpResponsePraser;
 
/**
 * EMAY http客户端
 * 
 * @author Frank
 *
 */
public class EmayHttpClient {
 
    /**
     * 链接超时时间(s)
     */
    private int httpConnectionTimeOut = 30;
 
    /**
     * 数据传输超时时间(s)
     */
    private int httpReadTimeOut = 30;
 
    public EmayHttpClient() {
 
    }
 
    /**
     * 
     * @param httpConnectionTimeOut
     *            链接超时时间(s)
     * @param httpReadTimeOut
     *            数据传输超时时间(s)
     */
    public EmayHttpClient(int httpConnectionTimeOut, int httpReadTimeOut) {
        this.httpConnectionTimeOut = httpConnectionTimeOut;
        this.httpReadTimeOut = httpReadTimeOut;
    }
 
    /**
     * 发送HTTP请求
     * 
     * @param request
     *            请求
     * @param praser
     *            响应解析器
     * @return T 响应
     */
    public <T> T service(EmayHttpRequest<?> request, EmayHttpResponsePraser<T> praser) {
        EmayHttpResultCode code = EmayHttpResultCode.SUCCESS;
        if (request.getUrl() == null || request.getUrl().length() == 0) {
            code = EmayHttpResultCode.ERROR_URL_NULL;
            return praser.prase(request.getCharSet(), code, 0, null, null, null);
        }
        HttpURLConnection conn = null;
        int httpCode = 0;
        Map<String, String> headers = null;
        List<String> cookies = null;
        ByteArrayOutputStream outputStream = null;
        try {
            conn = this.createConnection(request);
            this.fillConnection(conn, request);
            this.request(conn, request);
            httpCode = conn.getResponseCode();
            headers = this.getHeaders(conn, request.getCharSet());
            cookies = this.getCookies(conn, request.getCharSet());
            outputStream = this.getResultOutputStream(conn);
        } catch (KeyManagementException e) {
            code = EmayHttpResultCode.ERROR_HTTPS_SSL;
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            code = EmayHttpResultCode.ERROR_HTTPS_SSL;
            e.printStackTrace();
        } catch (ProtocolException e) {
            code = EmayHttpResultCode.ERROR_METHOD;
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            code = EmayHttpResultCode.ERROR_CHARSET;
            e.printStackTrace();
        } catch (MalformedURLException e) {
            code = EmayHttpResultCode.ERROR_URL;
            httpCode = 500;
            e.printStackTrace();
        } catch (IOException e) {
            code = EmayHttpResultCode.ERROR_CONNECT;
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        T t = null;
        try {
            t = praser.prase(request.getCharSet(), code, httpCode, headers, cookies, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return t;
    }
 
    /**
     * 获取HTTP响应头
     * 
     * @param conn
     * @param charSet
     * @return
     * @throws UnsupportedEncodingException
     */
    private Map<String, String> getHeaders(HttpURLConnection conn, String charSet) throws UnsupportedEncodingException {
        Map<String, String> resultHeaders = new HashMap<String, String>();
        Map<String, List<String>> header = conn.getHeaderFields();
        if (header != null && header.size() > 0) {
            for (Entry<String, List<String>> entry : header.entrySet()) {
                if (!"Set-Cookie".equalsIgnoreCase(entry.getKey())) {
                    String valuer = "";
                    if (entry.getValue() != null && entry.getValue().size() > 0) {
                        for (String value : entry.getValue()) {
                            valuer += new String(value.getBytes("ISO-8859-1"), charSet) + ",";
                        }
                        valuer = valuer.substring(0, valuer.length() - 1);
                    }
                    resultHeaders.put(entry.getKey(), valuer);
                }
            }
        }
        return resultHeaders;
    }
 
    /**
     * 获取HTTP响应Cookies
     * 
     * @param conn
     * @param charSet
     * @return
     * @throws UnsupportedEncodingException
     */
    private List<String> getCookies(HttpURLConnection conn, String charSet) throws UnsupportedEncodingException {
        List<String> resultC = new ArrayList<String>();
        List<String> cookies = null;
        Map<String, List<String>> header = conn.getHeaderFields();
        if (header != null && header.size() > 0) {
            cookies = header.get("Set-Cookie");
        }
        if (cookies != null) {
            for (String cookie : cookies) {
                resultC.add(new String(cookie.getBytes("ISO-8859-1"), charSet));
            }
        }
        return cookies;
    }
 
    /**
     * 获取HTTP响应数据流
     * 
     * @param conn
     * @return
     * @throws IOException
     */
    private ByteArrayOutputStream getResultOutputStream(HttpURLConnection conn) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        InputStream is = conn.getInputStream();
        try {
            if (is != null) {
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return outStream;
    }
 
    /**
     * 发送Http请求
     * 
     * @param conn
     * @param request
     * @throws IOException
     */
    private void request(HttpURLConnection conn, EmayHttpRequest<?> request) throws IOException {
        if (request.getMethod().equalsIgnoreCase("POST")) {
            conn.setDoOutput(true);
            // conn.connect();
            if (request.getParams() != null) {
                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                out.write(request.paramsToBytesForPost());
                out.flush();
                out.close();
            }
        } else {
            conn.connect();
        }
    }
 
    /**
     * 添加请求信息
     * 
     * @param conn
     * @param request
     * @throws ProtocolException
     */
    private void fillConnection(HttpURLConnection conn, EmayHttpRequest<?> request) throws ProtocolException {
        this.fillTimeout(conn);
        this.filleMethod(conn, request);
        this.fillHeaders(conn, request);
        this.fillCookies(conn, request);
    }
 
    /**
     * 添加超时时间
     * 
     * @param conn
     */
    private void fillTimeout(HttpURLConnection conn) {
        if (httpConnectionTimeOut != 0) {
            conn.setConnectTimeout(httpConnectionTimeOut * 1000);
        }
        if (httpReadTimeOut != 0) {
            conn.setReadTimeout(httpReadTimeOut * 1000);
        }
    }
 
    /**
     * 指定HTTP方法
     * 
     * @param conn
     * @param request
     * @throws ProtocolException
     */
    private void filleMethod(HttpURLConnection conn, EmayHttpRequest<?> request) throws ProtocolException {
        conn.setRequestMethod(request.getMethod().toUpperCase());
    }
 
    /**
     * 添加头信息
     * 
     * @param conn
     * @param request
     */
    private void fillHeaders(HttpURLConnection conn, EmayHttpRequest<?> request) {
        if (request.getHeaders() != null) {
            for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
    }
 
    /**
     * 添加Cookies
     * 
     * @param conn
     * @param request
     */
    private void fillCookies(HttpURLConnection conn, EmayHttpRequest<?> request) {
        if (request.getCookies() != null) {
            conn.setRequestProperty("Cookie", request.getCookies());
        }
    }
 
    /**
     * 创建Http链接
     * 
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws MalformedURLException
     * @throws IOException
     */
    private HttpURLConnection createConnection(EmayHttpRequest<?> request) throws NoSuchAlgorithmException, KeyManagementException, MalformedURLException, IOException {
        URL console = new URL(request.getUrl());
        HttpURLConnection conn;
        if (request.isHttps()) {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new X509TrustManager() {
 
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
 
                }
 
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
 
                }
 
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[] {};
                }
 
            } }, new java.security.SecureRandom());
            HttpsURLConnection sconn = (HttpsURLConnection) console.openConnection();
            sconn.setSSLSocketFactory(sc.getSocketFactory());
            sconn.setHostnameVerifier(new HostnameVerifier() {
 
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
 
            });
            conn = sconn;
        } else {
            conn = (HttpURLConnection) console.openConnection();
        }
        return conn;
    }
 
}