chenjiahe
2022-06-17 8af9b52e63967575713d77ad23b43d29d9826dc7
提交 | 用户 | age
5c5945 1 package com.hx.mp.util;
E 2
3 import java.io.BufferedOutputStream;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.net.HttpURLConnection;
10 import java.security.KeyManagementException;
11 import java.security.KeyStoreException;
12 import java.security.NoSuchAlgorithmException;
13 import java.security.UnrecoverableKeyException;
14 import java.security.cert.CertificateException;
15 import java.security.cert.X509Certificate;
16 import java.util.Iterator;
17 import java.util.Map;
18 import java.util.Set;
19 import java.util.SortedMap;
20
21 import javax.net.ssl.HttpsURLConnection;
22 import javax.net.ssl.SSLContext;
23 import javax.net.ssl.SSLSocketFactory;
24
25 import org.dom4j.Document;
26 import org.dom4j.DocumentHelper;
27 import org.dom4j.Element;
28
29 /**
30  * �Ƹ�ͨhttp����https����ͨ�ſͻ���<br/>
31  * ========================================================================<br/>
32  * api˵����<br/>
33  * setReqContent($reqContent),�����������ݣ�����post��get������get��ʽ�ṩ<br/>
34  * getResContent(), ��ȡӦ������<br/>
35  * setMethod(method),�������󷽷�,post����get<br/>
36  * getErrInfo(),��ȡ������Ϣ<br/>
37  * setCertInfo(certFile, certPasswd),����֤�飬˫��httpsʱ��Ҫʹ��<br/>
38  * setCaInfo(caFile), ����CA����ʽδpem���������򲻼��<br/>
39  * setTimeOut(timeOut)�� ���ó�ʱʱ�䣬��λ��<br/>
40  * getResponseCode(), ȡ���ص�http״̬��<br/>
41  * call(),������ýӿ�<br/>
42  * getCharset()/setCharset(),�ַ����<br/>
43  * 
44  * ========================================================================<br/>
45  *
46  */
47 public class TenpayHttpClient {
48     
49     private static final String USER_AGENT_VALUE = 
50         "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)";
51     
52     private static final String JKS_CA_FILENAME = 
53         "tenpay_cacert.jks";
54     
55     private static final String JKS_CA_ALIAS = "tenpay";
56     
57     private static final String JKS_CA_PASSWORD = "";
58     
59     /** ca֤���ļ� */
60     private File caFile;
61     
62     /** ֤���ļ� */
63     private File certFile;
64     
65     /** ֤������ */
66     private String certPasswd;
67     
68     /** �������ݣ�����post��get������get��ʽ�ṩ */
69     private String reqContent;
70     
71     /** Ӧ������ */
72     private String resContent;
73     
74     /** ���󷽷� */
75     private String method;
76     
77     /** ������Ϣ */
78     private String errInfo;
79     
80     /** ��ʱʱ��,����Ϊ��λ */
81     private int timeOut;
82     
83     /** httpӦ����� */
84     private int responseCode;
85     
86     /** �ַ���� */
87     private String charset;
88     
89     private InputStream inputStream;
90
91     private RequestHandler reqHandler;//方便取值所用(quan)
92     
93     /*public TenpayHttpClient() {
94         this.caFile = null;
95         this.certFile = null;
96         this.certPasswd = "";
97         
98         this.reqContent = "";
99         this.resContent = "";
100         this.method = "POST";
101         this.errInfo = "";
102         this.timeOut = 30;//30��
103         
104         this.responseCode = 0;
105         this.charset = "UTF-8";
106         
107         this.inputStream = null;
108     }*/
109     
110     public TenpayHttpClient() {
111         this.caFile = null;
112         this.certFile = null;
113         this.certPasswd = "";
114         
115         this.reqContent = "";
116         this.resContent = "";
117         this.method = "POST";
118         this.errInfo = "";
119         this.timeOut = 30;//30��
120         
121         this.responseCode = 0;
122         this.charset = "UTF-8";
123         
124         this.inputStream = null;
125     }
126
127     /**
128      * ����֤����Ϣ
129      * @param certFile ֤���ļ�
130      * @param certPasswd ֤������
131      */
132     public void setCertInfo(File certFile, String certPasswd) {
133         this.certFile = certFile;
134         this.certPasswd = certPasswd;
135     }
136     
137     /**
138      * ����ca
139      * @param caFile
140      */
141     public void setCaInfo(File caFile) {
142         this.caFile = caFile;
143     }
144     
145     /**
146      * ������������
147      * @param reqContent ��������
148      */
149     public void setReqContent(String reqContent) {
150         this.reqContent = reqContent;
151     }
152     
153     /**
154      * ��ȡ�������
155      * @return String
156      * @throws IOException 
157      */
158     public String getResContent() {
159         try {
160             this.doResponse();
161         } catch (IOException e) {
162             this.errInfo = e.getMessage();
163             //return "";
164         }
165         
166         return this.resContent;
167     }
168     
169     /**
170      * �������󷽷�post����get
171      * @param method ���󷽷�post/get
172      */
173     public void setMethod(String method) {
174         this.method = method;
175     }
176     
177     /**
178      * ��ȡ������Ϣ
179      * @return String
180      */
181     public String getErrInfo() {
182         return this.errInfo;
183     }
184     
185     /**
186      * ���ó�ʱʱ��,����Ϊ��λ
187      * @param timeOut ��ʱʱ��,����Ϊ��λ
188      */
189     public void setTimeOut(int timeOut) {
190         this.timeOut = timeOut;
191     }
192     
193     /**
194      * ��ȡhttp״̬��
195      * @return int
196      */
197     public int getResponseCode() {
198         return this.responseCode;
199     }
200     
201     /**
202      * ִ��http���á�true:�ɹ� false:ʧ��
203      * @return boolean
204      */
205 /*    public boolean call() {
206         
207         boolean isRet = false;
208         
209         
210         //http
211         if(null == this.caFile && null == this.certFile) {
212             System.out.println("没有CA");
213             try {
214                 this.callHttp();
215                 isRet = true;
216             } catch (IOException e) {
217                 this.errInfo = e.getMessage();
218             }
219             return isRet;
220         }
221         
222         //https
223         try {
224             this.callHttps();
225             isRet = true;
226         } catch (UnrecoverableKeyException e) {
227             this.errInfo = e.getMessage();
228         } catch (KeyManagementException e) {
229             this.errInfo = e.getMessage();
230         } catch (CertificateException e) {
231             this.errInfo = e.getMessage();
232         } catch (KeyStoreException e) {
233             this.errInfo = e.getMessage();
234         } catch (NoSuchAlgorithmException e) {
235             this.errInfo = e.getMessage();
236         } catch (IOException e) {
237             this.errInfo = e.getMessage();
238         }
239         
240         return isRet;
241         
242     }*/
243     
244     /**
245      * ִ��http���á�true:�ɹ� false:ʧ��
246      * @return boolean
247      */
248     public boolean call() {
249         
250         boolean isRet = false;
251         
252         
253         //http
254         if(null == this.caFile && null == this.certFile) {
255             System.out.println("没有CA");
256             try {
257                 this.callHttp();
258                 isRet = true;
259             } catch (IOException e) {
260                 this.errInfo = e.getMessage();
261             }
262             return isRet;
263         }
264         
265         //https
266         try {
267             this.callHttps();
268             isRet = true;
269         } catch (UnrecoverableKeyException e) {
270             this.errInfo = e.getMessage();
271         } catch (KeyManagementException e) {
272             this.errInfo = e.getMessage();
273         } catch (CertificateException e) {
274             this.errInfo = e.getMessage();
275         } catch (KeyStoreException e) {
276             this.errInfo = e.getMessage();
277         } catch (NoSuchAlgorithmException e) {
278             this.errInfo = e.getMessage();
279         } catch (IOException e) {
280             this.errInfo = e.getMessage();
281         }
282         
283         return isRet;
284         
285     }
286     
287     protected void callHttp() throws IOException {
288         
289         if("POST".equals(this.method.toUpperCase())) {
290             String url = HttpClientUtil.getURL(this.reqContent);
291             System.out.println("tenpayHttpClient:url:"+url);
292             //String queryString = HttpClientUtil.getQueryString(this.reqContent);
293             //byte[] postData = queryString.getBytes(this.charset);
294             
295             String queryString = createXmlPosData();
296             byte[] postData = queryString.getBytes(this.charset);
297             this.httpPostMethod(url, postData);
298             
299             return ;
300         }
301         
302         this.httpGetMethod(this.reqContent);
303         
304     } 
305     
306     protected void callHttps() throws IOException, CertificateException,
307             KeyStoreException, NoSuchAlgorithmException,
308             UnrecoverableKeyException, KeyManagementException {
309         // caĿ¼
310         String caPath = this.caFile.getParent();
311
312         System.out.println("caPath:"+caPath);
313         File jksCAFile = new File(caPath + "/"
314                 + TenpayHttpClient.JKS_CA_FILENAME);
315         if (!jksCAFile.isFile()) {
316             X509Certificate cert = (X509Certificate) HttpClientUtil
317                     .getCertificate(this.caFile);
318
319             FileOutputStream out = new FileOutputStream(jksCAFile);
320
321             // store jks file
322             HttpClientUtil.storeCACert(cert, TenpayHttpClient.JKS_CA_ALIAS,
323                     TenpayHttpClient.JKS_CA_PASSWORD, out);
324
325             out.close();
326
327         }
328
329         FileInputStream trustStream = new FileInputStream(jksCAFile);
330         FileInputStream keyStream = new FileInputStream(this.certFile);
331
332         SSLContext sslContext = HttpClientUtil.getSSLContext(trustStream,
333                 TenpayHttpClient.JKS_CA_PASSWORD, keyStream, this.certPasswd);
334         
335         //�ر���
336         keyStream.close();
337         trustStream.close();
338         
339         if("POST".equals(this.method.toUpperCase())) {
340             String url = HttpClientUtil.getURL(this.reqContent);
341             
342             //原本是直接参数转为字节数组的,现在组拼xml
343             //String queryString = HttpClientUtil.getQueryString(this.reqContent);//获取链接下面的内容
344             //byte[] postData = queryString.getBytes(this.charset);//把参数转为字节数组
345             
346             //先获取参数
347             String queryString = createXmlPosData();    
348             
349             byte[] postData = queryString.getBytes(this.charset);//把参数转为字节数组
350             
351             this.httpsPostMethod(url, postData, sslContext);
352             
353             return ;
354         }
355         
356         this.httpsGetMethod(this.reqContent, sslContext);
357
358     }
359     
360     /**
361      * ��http post��ʽͨ��
362      * @param url
363      * @param postData
364      * @throws IOException
365      */
366     protected void httpPostMethod(String url, byte[] postData)
367             throws IOException {
368
369         HttpURLConnection conn = HttpClientUtil.getHttpURLConnection(url);
370
371         this.doPost(conn, postData);
372     }
373     
374     /**
375      * ��http get��ʽͨ��
376      * 
377      * @param url
378      * @throws IOException
379      */
380     protected void httpGetMethod(String url) throws IOException {
381         
382         HttpURLConnection httpConnection =
383             HttpClientUtil.getHttpURLConnection(url);
384         
385         this.setHttpRequest(httpConnection);
386         
387         httpConnection.setRequestMethod("GET");
388         
389         this.responseCode = httpConnection.getResponseCode();
390         
391         this.inputStream = httpConnection.getInputStream();
392         
393     }
394     
395     /**
396      * ��https get��ʽͨ��
397      * @param url
398      * @param sslContext
399      * @throws IOException
400      */
401     protected void httpsGetMethod(String url, SSLContext sslContext)
402             throws IOException {
403
404         SSLSocketFactory sf = sslContext.getSocketFactory();
405
406         HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);
407
408         conn.setSSLSocketFactory(sf);
409
410         this.doGet(conn);
411
412     }
413     
414     //提交https post 数据 s
415     protected void httpsPostMethod(String url, byte[] postData,
416             SSLContext sslContext) throws IOException {
417
418         SSLSocketFactory sf = sslContext.getSocketFactory();
419
420         HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);
421
422         conn.setSSLSocketFactory(sf);
423
424         this.doPost(conn, postData);
425
426     }
427     
428     /**
429      * ����http����Ĭ������
430      * @param httpConnection
431      */
432     protected void setHttpRequest(HttpURLConnection httpConnection) {
433         
434         //�������ӳ�ʱʱ��
435         httpConnection.setConnectTimeout(this.timeOut * 1000);
436         
437         //User-Agent
438         httpConnection.setRequestProperty("User-Agent", 
439                 TenpayHttpClient.USER_AGENT_VALUE);
440         
441         //��ʹ�û���
442         httpConnection.setUseCaches(false);
443         
444         //�����������
445         httpConnection.setDoInput(true);
446         httpConnection.setDoOutput(true);
447         
448     }
449     
450     /**
451      * ����Ӧ��
452      * @throws IOException
453      */
454     protected void doResponse() throws IOException {
455         
456         if(null == this.inputStream) {
457             return;
458         }
459
460         //��ȡӦ������
461         this.resContent=HttpClientUtil.InputStreamTOString(this.inputStream,this.charset); 
462         
463     //    System.out.println("tenpayHttpClinet:385:"+resContent);
464         //�ر�������
465         this.inputStream.close();
466         
467     }
468     
469     /**
470      * post��ʽ����
471      * @param conn
472      * @param postData
473      * @throws IOException
474      */
475     protected void doPost(HttpURLConnection conn, byte[] postData)
476             throws IOException {
477
478         // ��post��ʽͨ��
479         conn.setRequestMethod("POST");
480
481         // ��������Ĭ������
482         this.setHttpRequest(conn);
483
484         // Content-Type
485         conn.setRequestProperty("Content-Type",
486                 "application/x-www-form-urlencoded");
487
488         BufferedOutputStream out = new BufferedOutputStream(conn
489                 .getOutputStream());
490
491         final int len = 1024; // 1KB
492         HttpClientUtil.doOutput(out, postData, len);
493
494         // �ر���
495         out.close();
496
497         // ��ȡ��Ӧ����״̬��
498         this.responseCode = conn.getResponseCode();
499
500         // ��ȡӦ��������
501         this.inputStream = conn.getInputStream();
502
503     }
504     
505     /**
506      * get��ʽ����
507      * @param conn
508      * @throws IOException
509      */
510     protected void doGet(HttpURLConnection conn) throws IOException {
511         
512         //��GET��ʽͨ��
513         conn.setRequestMethod("GET");
514         
515         //��������Ĭ������
516         this.setHttpRequest(conn);
517         
518         //��ȡ��Ӧ����״̬��
519         this.responseCode = conn.getResponseCode();
520         
521         //��ȡӦ��������
522         this.inputStream = conn.getInputStream();
523     }
524     
525     public void setRequestHandler(RequestHandler reqHandler) {
526         this.reqHandler = reqHandler;
527     }
528     
529     
530     //组建xml格式传递参数
531     @SuppressWarnings({ "rawtypes", "unused" })
532     public String createXmlPosData(){
533         //先获取参数
534         Document document = DocumentHelper.createDocument();
535         Element root = document.addElement("xml");
536         
537         if(reqHandler==null)throw new RuntimeException("请先设入reqHandler");
538         
539         SortedMap parameters = reqHandler.getAllParameters();
540         Set es = reqHandler.getAllParameters().entrySet();
541         Iterator it = es.iterator();
542         while(it.hasNext()) {
543             Map.Entry entry = (Map.Entry)it.next();
544             String k = (String)entry.getKey();
545             String v = (String)entry.getValue();
546             
547             Element ToUserName = root.addElement(k);
548             ToUserName.addText(v);
549         }
550         
551         String queryString = document.asXML();//转为String
552         
553         queryString = queryString.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").trim();
554         
555         System.out.println("xml:"+queryString);
556         return queryString;
557     }
558     
559 }