chenjiahe
2022-03-31 b5bfe58beeeeb8343bdea6a9412f8f6704b67633
提交 | 用户 | age
5c5945 1 package com.hx.mp.util;
E 2
3 import java.io.BufferedReader;
4 import java.io.ByteArrayInputStream;
5 import java.io.ByteArrayOutputStream;
6 import java.io.File;
7 import java.io.FileInputStream;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.OutputStream;
11 import java.net.HttpURLConnection;
12 import java.net.URL;
13 import java.security.KeyManagementException;
14 import java.security.KeyStore;
15 import java.security.KeyStoreException;
16 import java.security.NoSuchAlgorithmException;
17 import java.security.SecureRandom;
18 import java.security.UnrecoverableKeyException;
19 import java.security.cert.Certificate;
20 import java.security.cert.CertificateException;
21 import java.security.cert.CertificateFactory;
22 import java.util.HashMap;
23 import java.util.Map;
24
25 import javax.net.ssl.HttpsURLConnection;
26 import javax.net.ssl.KeyManagerFactory;
27 import javax.net.ssl.SSLContext;
28 import javax.net.ssl.TrustManagerFactory;
29
30 /**
31  * Http�ͻ��˹�����<br/>
32  * �����ڲ������࣬�벻Ҫ���ⲿ���á�
33  * @author miklchen
34  *
35  */
36 public class HttpClientUtil {
37     
38     public static final String SunX509 = "SunX509";
39     public static final String JKS = "JKS";
40     public static final String PKCS12 = "PKCS12";
41     public static final String TLS = "TLS";
42     
43     /**
44      * get HttpURLConnection
45      * @param strUrl url��ַ
46      * @return HttpURLConnection
47      * @throws IOException
48      */
49     public static HttpURLConnection getHttpURLConnection(String strUrl)
50             throws IOException {
51         URL url = new URL(strUrl);
52         HttpURLConnection httpURLConnection = (HttpURLConnection) url
53                 .openConnection();
54         return httpURLConnection;
55     }
56     
57     /**
58      * get HttpsURLConnection
59      * @param strUrl url��ַ
60      * @return HttpsURLConnection
61      * @throws IOException
62      */
63     public static HttpsURLConnection getHttpsURLConnection(String strUrl)
64             throws IOException {
65         URL url = new URL(strUrl);
66         HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url
67                 .openConnection();
68         return httpsURLConnection;
69     }
70     
71     /**
72      * ��ȡ�����ѯ����url
73      * @param strUrl
74      * @return String
75      */
76     public static String getURL(String strUrl) {
77
78         if(null != strUrl) {
79             int indexOf = strUrl.indexOf("?");
80             if(-1 != indexOf) {
81                 return strUrl.substring(0, indexOf);
82             } 
83             
84             return strUrl;
85         }
86         
87         return strUrl;
88         
89     }
90     
91     /**
92      * ��ȡ��ѯ��
93      * @param strUrl
94      * @return String
95      */
96     public static String getQueryString(String strUrl) {
97         
98         if(null != strUrl) {
99             int indexOf = strUrl.indexOf("?");
100             if(-1 != indexOf) {
101                 return strUrl.substring(indexOf+1, strUrl.length());
102             } 
103             
104             return "";
105         }
106         
107         return strUrl;
108     }
109     
110     /**
111      * ��ѯ�ַ�ת����Map<br/>
112      * name1=key1&name2=key2&...
113      * @param queryString
114      * @return
115      */
116     @SuppressWarnings("rawtypes")
117     public static Map queryString2Map(String queryString) {
118         if(null == queryString || "".equals(queryString)) {
119             return null;
120         }
121         
122         Map m = new HashMap();
123         String[] strArray = queryString.split("&");
124         for(int index = 0; index < strArray.length; index++) {
125             String pair = strArray[index];
126             HttpClientUtil.putMapByPair(pair, m);
127         }
128         
129         return m;
130         
131     }
132     
133     /**
134      * �Ѽ�ֵ�����Map<br/>
135      * pair:name=value
136      * @param pair name=value
137      * @param m
138      */
139     @SuppressWarnings({ "unchecked", "rawtypes" })
140     public static void putMapByPair(String pair, Map m) {
141         
142         if(null == pair || "".equals(pair)) {
143             return;
144         }
145         
146         int indexOf = pair.indexOf("=");
147         if(-1 != indexOf) {
148             String k = pair.substring(0, indexOf);
149             String v = pair.substring(indexOf+1, pair.length());
150             if(null != k && !"".equals(k)) {
151                 m.put(k, v);
152             }
153         } else {
154             m.put(pair, "");
155         }
156     }
157     
158     /**
159      * BufferedReaderת����String<br/>
160      * ע��:���ر���Ҫ���д���
161      * @param reader
162      * @return String
163      * @throws IOException
164      */
165     public static String bufferedReader2String(BufferedReader reader) throws IOException {
166         StringBuffer buf = new StringBuffer();
167         String line = null;
168         while( (line = reader.readLine()) != null) {
169             buf.append(line);
170             buf.append("\r\n");
171         }
172                 
173         return buf.toString();
174     }
175     
176     /**
177      * �������<br/>
178      * ע��:���ر���Ҫ���д���
179      * @param out
180      * @param data
181      * @param len
182      * @throws IOException
183      */
184     public static void doOutput(OutputStream out, byte[] data, int len)
185             throws IOException {
186         int dataLen = data.length;
187         int off = 0;
188         while (off < data.length) {
189             if (len >= dataLen) {
190                 out.write(data, off, dataLen);
191                 off += dataLen;
192             } else {
193                 out.write(data, off, len);
194                 off += len;
195                 dataLen -= len;
196             }
197
198             // ˢ�»�����
199             out.flush();
200         }
201
202     }
203     
204     /**
205      * ��ȡSSLContext
206      * @param trustFile 
207      * @param trustPasswd
208      * @param keyFile
209      * @param keyPasswd
210      * @return
211      * @throws NoSuchAlgorithmException 
212      * @throws KeyStoreException 
213      * @throws IOException 
214      * @throws CertificateException 
215      * @throws UnrecoverableKeyException 
216      * @throws KeyManagementException 
217      */
218     public static SSLContext getSSLContext(
219             FileInputStream trustFileInputStream, String trustPasswd,
220             FileInputStream keyFileInputStream, String keyPasswd)
221             throws NoSuchAlgorithmException, KeyStoreException,
222             CertificateException, IOException, UnrecoverableKeyException,
223             KeyManagementException {
224
225         // ca
226         TrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);
227         KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);
228         trustKeyStore.load(trustFileInputStream, HttpClientUtil
229                 .str2CharArray(trustPasswd));
230         tmf.init(trustKeyStore);
231
232         final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);
233         KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);
234         KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);
235         ks.load(keyFileInputStream, kp);
236         kmf.init(ks, kp);
237
238         SecureRandom rand = new SecureRandom();
239         SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);
240         ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);
241
242         return ctx;
243     }
244     
245     /**
246      * ��ȡCA֤����Ϣ
247      * @param cafile CA֤���ļ�
248      * @return Certificate
249      * @throws CertificateException
250      * @throws IOException
251      */
252     public static Certificate getCertificate(File cafile)
253             throws CertificateException, IOException {
254         CertificateFactory cf = CertificateFactory.getInstance("X.509");
255         FileInputStream in = new FileInputStream(cafile);
256         Certificate cert = cf.generateCertificate(in);
257         in.close();
258         return cert;
259     }
260     
261     /**
262      * �ַ�ת����char����
263      * @param str
264      * @return char[]
265      */
266     public static char[] str2CharArray(String str) {
267         if(null == str) return null;
268         
269         return str.toCharArray();
270     }
271     
272     /**
273      * �洢ca֤���JKS��ʽ
274      * @param cert
275      * @param alias
276      * @param password
277      * @param out
278      * @throws KeyStoreException
279      * @throws NoSuchAlgorithmException
280      * @throws CertificateException
281      * @throws IOException
282      */
283     public static void storeCACert(Certificate cert, String alias,
284             String password, OutputStream out) throws KeyStoreException,
285             NoSuchAlgorithmException, CertificateException, IOException {
286         KeyStore ks = KeyStore.getInstance("JKS");
287
288         ks.load(null, null);
289
290         ks.setCertificateEntry(alias, cert);
291
292         // store keystore
293         ks.store(out, HttpClientUtil.str2CharArray(password));
294
295     }
296     
297     public static InputStream String2Inputstream(String str) {
298         return new ByteArrayInputStream(str.getBytes());
299     }
300     
301     /**
302      * InputStreamת����Byte
303      * ע��:���ر���Ҫ���д���
304      * @param in
305      * @return byte
306      * @throws Exception
307      */
308     public static byte[] InputStreamTOByte(InputStream in) throws IOException{  
309         
310         int BUFFER_SIZE = 4096;  
311         ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
312         byte[] data = new byte[BUFFER_SIZE];  
313         int count = -1;  
314         
315         while((count = in.read(data,0,BUFFER_SIZE)) != -1)  
316             outStream.write(data, 0, count);  
317           
318         data = null;  
319         byte[] outByte = outStream.toByteArray();
320         outStream.close();
321         
322         return outByte;  
323     } 
324     
325     /**
326      * InputStreamת����String
327      * ע��:���ر���Ҫ���д���
328      * @param in
329      * @param encoding ����
330      * @return String
331      * @throws Exception
332      */
333     public static String InputStreamTOString(InputStream in,String encoding) throws IOException{  
334
335         return new String(InputStreamTOByte(in),encoding);
336         
337     }
338     
339
340 }