httpClinent工具类

  1 package com.juchn.gateway.common.utils;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.security.KeyManagementException;
  8 import java.security.KeyStoreException;
  9 import java.security.NoSuchAlgorithmException;
 10 import java.security.cert.CertificateException;
 11 import java.security.cert.X509Certificate;
 12 import java.util.ArrayList;
 13 import java.util.Iterator;
 14 import java.util.List;
 15 import java.util.Map;
 16 import java.util.Map.Entry;
 17 
 18 import javax.net.ssl.SSLContext;
 19 
 20 import org.apache.commons.lang3.StringUtils;
 21 import org.apache.http.HttpEntity;
 22 import org.apache.http.HttpHost;
 23 import org.apache.http.NameValuePair;
 24 import org.apache.http.ParseException;
 25 import org.apache.http.client.config.RequestConfig;
 26 import org.apache.http.client.entity.UrlEncodedFormEntity;
 27 import org.apache.http.client.methods.CloseableHttpResponse;
 28 import org.apache.http.client.methods.HttpGet;
 29 import org.apache.http.client.methods.HttpPost;
 30 import org.apache.http.client.methods.HttpPut;
 31 import org.apache.http.client.utils.URLEncodedUtils;
 32 import org.apache.http.conn.ssl.NoopHostnameVerifier;
 33 import org.apache.http.entity.StringEntity;
 34 import org.apache.http.impl.client.CloseableHttpClient;
 35 import org.apache.http.impl.client.HttpClients;
 36 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
 37 import org.apache.http.message.BasicNameValuePair;
 38 import org.apache.http.ssl.SSLContextBuilder;
 39 import org.apache.http.ssl.TrustStrategy;
 40 import org.apache.http.util.EntityUtils;
 41 import org.slf4j.Logger;
 42 import org.slf4j.LoggerFactory;
 43 
 44 /**
 45  * 新版httpClient的工具方法
 46  * 
 47  * @author tangzl
 48  * @since 2019年04月11日
 49  */
 50 public class HttpClientUtil {
 51 
 52     static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
 53     protected static final String CHARSET = "UTF-8";
 54     protected static final String CHARSET_GBK = "UTF-8";
 55     /** 默认超时时间 */
 56     private final static int default_timeout = 10000;
 57 
 58     private static PoolingHttpClientConnectionManager cm = null;
 59 
 60     private static CloseableHttpClient httpclient = null;
 61     static {
 62 
 63         // 多连接的线程安全的管理器
 64         cm = new PoolingHttpClientConnectionManager();
 65         cm.setDefaultMaxPerRoute(100); // 每个主机的最大并行链接数
 66         cm.setMaxTotal(200); // 客户端总并行链接最大数
 67 
 68         httpclient = HttpClients.custom().setConnectionManager(cm).build();
 69     }
 70 
 71     /**
 72      * 发送 get请求
 73      * 
 74      * @param url
 75      * @param timeout     超时时间
 76      * @param ignoreHttps 是否忽略https证书检查
 77      * @return
 78      */
 79     public static String get(String url, Map<String, String> params, Integer timeout, boolean ignoreHttps,
 80             HttpHost proxy) {
 81         CloseableHttpClient client = null;
 82         if (ignoreHttps) {
 83             client = getIgnoreHttpsClient();
 84         } else {
 85             client = httpclient;
 86         }
 87         try {
 88             HttpGet httpGet = null;
 89             if (params == null)
 90                 httpGet = new HttpGet(url);
 91             else {
 92                 List<NameValuePair> qparams = new ArrayList<NameValuePair>();
 93                 for (Entry<String, String> entry : params.entrySet()) {
 94                     qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
 95                 }
 96                 String queryParams = URLEncodedUtils.format(qparams, "UTF-8");
 97                 if (url.indexOf("?") != -1) {
 98                     url += "&" + queryParams;
 99                 } else {
100                     url += "?" + queryParams;
101                 }
102                 httpGet = new HttpGet(url);
103             }
104             timeout = timeout != null ? timeout : default_timeout;
105             RequestConfig.Builder builder = RequestConfig.custom();// 设置请求和传输超时时间
106             if (null != proxy) {
107                 builder.setProxy(proxy);
108             }
109             RequestConfig requestConfig = builder.setSocketTimeout(timeout).setConnectTimeout(timeout).build();// 设置请求和传输超时时间
110             httpGet.setConfig(requestConfig);
111 
112             CloseableHttpResponse response = client.execute(httpGet);
113             HttpEntity entity = response.getEntity();
114             try {
115                 if (entity != null)
116                     return EntityUtils.toString(entity);
117             } finally {
118                 if (entity != null)
119                     EntityUtils.consume(entity);
120                 response.close();
121             }
122         } catch (ParseException e) {
123             log.error("发送HTTP请求时出现异常:" + e);
124             e.printStackTrace(System.out);
125         } catch (IOException e) {
126             log.error("发送HTTP请求时出现异常:" + e);
127             e.printStackTrace(System.out);
128         } catch (Exception e) {
129             log.error("发送HTTP请求时出现异常:" + e);
130             e.printStackTrace(System.out);
131         } finally {
132             /*
133              * try { httpclient.close(); } catch (IOException e) {
134              * log.error("关闭HTTP连接时出现异常:" + e); }
135              */
136         }
137         return null;
138     }
139 
140     /**
141      * 发送 get请求
142      * 
143      * @param url
144      * @param timeout     超时时间
145      * @param ignoreHttps 是否忽略https证书检查
146      * @return
147      */
148     public static String get(String url, Map<String, String> params, Map<String, Object> headers, Integer timeout,
149             boolean ignoreHttps) {
150         CloseableHttpClient client = null;
151         if (ignoreHttps) {
152             client = getIgnoreHttpsClient();
153         } else {
154             client = httpclient;
155         }
156         try {
157             HttpGet httpGet = null;
158             if (params != null && params.size() > 0) {
159                 List<NameValuePair> qparams = new ArrayList<NameValuePair>();
160                 for (Entry<String, String> entry : params.entrySet()) {
161                     qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
162                 }
163                 String queryParams = URLEncodedUtils.format(qparams, "UTF-8");
164                 if (url.indexOf("?") != -1) {
165                     url += "&" + queryParams;
166                 } else {
167                     url += "?" + queryParams;
168                 }
169 
170             }
171             httpGet = new HttpGet(url);
172             httpGet.setHeader("Content-type", "application/json;charset=UTF-8");
173             if (headers != null && headers.size() > 0) {
174                 for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
175                     String key = iter.next();
176                     httpGet.setHeader(key, headers.get(key).toString());
177                 }
178             }
179 
180             timeout = timeout != null ? timeout : default_timeout;
181             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
182                     .build();// 设置请求和传输超时时间
183             httpGet.setConfig(requestConfig);
184 
185             CloseableHttpResponse response = client.execute(httpGet);
186             HttpEntity entity = response.getEntity();
187             try {
188                 if (entity != null)
189                     return EntityUtils.toString(entity);
190             } finally {
191                 if (entity != null)
192                     EntityUtils.consume(entity);
193                 response.close();
194             }
195         } catch (ParseException e) {
196             log.error("发送HTTP请求时出现异常:" + e);
197             e.printStackTrace(System.out);
198         } catch (IOException e) {
199             log.error("发送HTTP请求时出现异常:" + e);
200             e.printStackTrace(System.out);
201         } catch (Exception e) {
202             log.error("发送HTTP请求时出现异常:" + e);
203             e.printStackTrace(System.out);
204         } finally {
205             /*
206              * try { httpclient.close(); } catch (IOException e) {
207              * log.error("关闭HTTP连接时出现异常:" + e); }
208              */
209         }
210         return null;
211     }
212 
213     /**
214      * 发送 get请求
215      * 
216      * @param url
217      * @param timeout     超时时间
218      * @param ignoreHttps 是否忽略https证书检查
219      * @return
220      */
221     public static String get(String url, Map<String, String> params, Integer timeout, boolean ignoreHttps) {
222         CloseableHttpClient client = null;
223         if (ignoreHttps) {
224             client = getIgnoreHttpsClient();
225         } else {
226             client = httpclient;
227         }
228         try {
229             HttpGet httpGet = null;
230             if (params == null)
231                 httpGet = new HttpGet(url);
232             else {
233                 List<NameValuePair> qparams = new ArrayList<NameValuePair>();
234                 for (Entry<String, String> entry : params.entrySet()) {
235                     qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
236                 }
237                 String queryParams = URLEncodedUtils.format(qparams, "UTF-8");
238                 if (url.indexOf("?") != -1) {
239                     url += "&" + queryParams;
240                 } else {
241                     url += "?" + queryParams;
242                 }
243                 httpGet = new HttpGet(url);
244             }
245             timeout = timeout != null ? timeout : default_timeout;
246             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
247                     .build();// 设置请求和传输超时时间
248             httpGet.setConfig(requestConfig);
249 
250             CloseableHttpResponse response = client.execute(httpGet);
251             HttpEntity entity = response.getEntity();
252             try {
253                 if (entity != null)
254                     return EntityUtils.toString(entity);
255             } finally {
256                 if (entity != null)
257                     EntityUtils.consume(entity);
258                 response.close();
259             }
260         } catch (ParseException e) {
261             log.error("发送HTTP请求时出现异常:" + e);
262             e.printStackTrace(System.out);
263         } catch (IOException e) {
264             log.error("发送HTTP请求时出现异常:" + e);
265             e.printStackTrace(System.out);
266         } catch (Exception e) {
267             log.error("发送HTTP请求时出现异常:" + e);
268             e.printStackTrace(System.out);
269         } finally {
270             /*
271              * try { httpclient.close(); } catch (IOException e) {
272              * log.error("关闭HTTP连接时出现异常:" + e); }
273              */
274         }
275         return null;
276     }
277 
278     /**
279      * 发送get请求
280      * 
281      * @param url
282      * @param timeout 超时时间(毫秒)
283      * @return
284      */
285     public static String get(String url, Map<String, String> params, Integer timeout) {
286         return get(url, params, timeout, false);
287     }
288 
289     /**
290      * 发送get请求
291      * 
292      * @param url
293      * @param timeout 超时时间(毫秒)
294      * @return
295      */
296     public static String get(String url, Map<String, String> params, Map<String, Object> headers) {
297         return get(url, params, headers, null, false);
298     }
299 
300     /**
301      * 发送 get请求
302      * 
303      * @param url
304      * @param timeout     超时时间
305      * @param ignoreHttps 是否忽略https证书检查
306      * @return
307      */
308     public static String get(String url, Integer timeout, boolean ignoreHttps) {
309         return get(url, null, timeout, ignoreHttps);
310     }
311 
312     /**
313      * 获取忽略https证书的client
314      * 
315      * @return
316      */
317     public static CloseableHttpClient getIgnoreHttpsClient() {
318         SSLContext sslContext = null;
319         try {
320             sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
321                 public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
322                     return true;
323                 }
324             }).build();
325         } catch (KeyManagementException e) {
326             e.printStackTrace();
327         } catch (NoSuchAlgorithmException e) {
328             e.printStackTrace();
329         } catch (KeyStoreException e) {
330             e.printStackTrace();
331         }
332 
333         return HttpClients.custom().setSslcontext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier())
334                 .build();
335     }
336 
337     /**
338      * 发送 post请求
339      * 
340      * @param url
341      * @param timeout 超时时间(毫秒)
342      * @param params  请求参数
343      * @return
344      */
345     public static String post(String url, Map<String, String> params, Integer timeout) {
346 
347         CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
348         try {
349 
350             HttpPost httpPost = new HttpPost(url);
351             if (params != null) {
352                 List<NameValuePair> qparams = new ArrayList<NameValuePair>();
353                 for (Entry<String, String> entry : params.entrySet()) {
354                     qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
355                 }
356                 httpPost.setEntity(new UrlEncodedFormEntity(qparams, "UTF-8"));
357             }
358             timeout = timeout != null ? timeout : default_timeout;
359             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
360                     .build();// 设置请求和传输超时时间
361             httpPost.setConfig(requestConfig);
362 
363             CloseableHttpResponse response = httpclient.execute(httpPost);
364             HttpEntity entity = response.getEntity();
365             try {
366                 if (entity != null) {
367                     StringBuilder sb = new StringBuilder();
368                     String line = null;
369                     InputStream inputStream = entity.getContent();
370                     try {
371                         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
372                         while ((line = bufferedReader.readLine()) != null) {
373                             sb.append(line);
374                         }
375                     } finally {
376                         inputStream.close();
377                     }
378                     return sb.toString();
379                 }
380             } finally {
381                 response.close();
382             }
383 
384             /*
385              * try { if (entity != null) return EntityUtils.toString(entity); } finally { if
386              * (entity != null) EntityUtils.consume(entity); response.close(); }
387              */
388         } catch (ParseException e) {
389             log.error("发送HTTP请求时出现异常:" + e);
390             e.printStackTrace(System.out);
391         } catch (IOException e) {
392             log.error("发送HTTP请求时出现异常:" + e);
393             e.printStackTrace(System.out);
394         } catch (Exception e) {
395             log.error("发送HTTP请求时出现异常:" + e);
396             e.printStackTrace(System.out);
397         } finally {
398             /*
399              * try { httpclient.close(); } catch (IOException e) {
400              * log.error("关闭HTTP连接时出现异常:" + e); }
401              */
402         }
403         return null;
404     }
405 
406     /**
407      * 发送 post请求 带请求头
408      * 
409      * @param url
410      * @param params
411      * @param headers
412      * @param timeout
413      * @return
414      */
415     public static String post(String url, Map<String, String> params, Map<String, String> headers, Integer timeout) {
416 
417         CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
418         try {
419             HttpPost httpPost = new HttpPost(url);
420 
421             if (params != null) {
422                 List<NameValuePair> qparams = new ArrayList<NameValuePair>();
423                 for (Entry<String, String> entry : params.entrySet()) {
424                     qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
425                 }
426                 httpPost.setEntity(new UrlEncodedFormEntity(qparams, CHARSET));
427             }
428             if (headers != null && headers.size() > 0) {
429                 for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
430                     String key = iter.next();
431                     httpPost.setHeader(key, headers.get(key));
432                 }
433             }
434             timeout = timeout != null ? timeout : default_timeout;
435             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
436                     .build();// 设置请求和传输超时时间
437             httpPost.setConfig(requestConfig);
438 
439             CloseableHttpResponse response = httpclient.execute(httpPost);
440             HttpEntity entity = response.getEntity();
441 
442             // 方法一:
443             try {
444                 if (entity != null) {
445                     StringBuilder sb = new StringBuilder();
446                     String line = null;
447                     InputStream inputStream = entity.getContent();
448                     try {
449                         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
450                         while ((line = bufferedReader.readLine()) != null) {
451                             sb.append(line);
452                         }
453                     } finally {
454                         inputStream.close();
455                     }
456                     return sb.toString();
457                 }
458             } finally {
459                 response.close();
460             }
461 
462             // 方法二:
463             /*
464              * try { if (entity != null) return EntityUtils.toString(entity); } finally { if
465              * (entity != null) EntityUtils.consume(entity); response.close(); }
466              */
467         } catch (ParseException e) {
468             log.error("发送HTTP请求时出现异常:" + e);
469             e.printStackTrace(System.out);
470         } catch (IOException e) {
471             log.error("发送HTTP请求时出现异常:" + e);
472             e.printStackTrace(System.out);
473         } catch (Exception e) {
474             log.error("发送HTTP请求时出现异常:" + e);
475             e.printStackTrace(System.out);
476         } finally {
477             /*
478              * try { httpclient.close(); } catch (IOException e) {
479              * log.error("关闭HTTP连接时出现异常:" + e); }
480              */
481         }
482         return null;
483     }
484 
485     /**
486      * post body
487      * 
488      * @param url
489      * @param params 请求body内容
490      * @return
491      */
492     public static String postBody(String url, String params, Map<String, String> headers, Integer timeout) {
493 
494         CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
495         try {
496 
497             HttpPost httpPost = new HttpPost(url);
498             if (!StringUtils.isEmpty(params)) {
499                 httpPost.setEntity(new StringEntity(params, "UTF-8"));
500             }
501             if (headers != null && headers.size() > 0) {
502                 for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
503                     String key = iter.next();
504                     httpPost.setHeader(key, headers.get(key));
505                 }
506             }
507             timeout = timeout != null ? timeout : default_timeout;
508             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
509                     .build();// 设置请求和传输超时时间
510             httpPost.setConfig(requestConfig);
511 
512             CloseableHttpResponse response = httpclient.execute(httpPost);
513             HttpEntity entity = response.getEntity();
514             // 方法一:
515             try {
516                 if (entity != null) {
517                     StringBuilder sb = new StringBuilder();
518                     String line = null;
519                     InputStream inputStream = entity.getContent();
520                     try {
521                         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
522                         while ((line = bufferedReader.readLine()) != null) {
523                             sb.append(line);
524                         }
525                     } finally {
526                         inputStream.close();
527                     }
528                     return sb.toString();
529                 }
530             } finally {
531                 response.close();
532             }
533             // 方法二:
534             /*
535              * try { if (entity != null) return EntityUtils.toString(entity); } finally { if
536              * (entity != null) EntityUtils.consume(entity); response.close(); }
537              */
538         } catch (ParseException e) {
539             log.error("发送HTTP请求时出现异常:" + e);
540             e.printStackTrace(System.out);
541         } catch (IOException e) {
542             log.error("发送HTTP请求时出现异常:" + e);
543             e.printStackTrace(System.out);
544         } catch (Exception e) {
545             log.error("发送HTTP请求时出现异常:" + e);
546             e.printStackTrace(System.out);
547         } finally {
548         }
549         return null;
550     }
551 
552     public static String postBodyJson(String url, String params, Map<String, String> headers, Integer timeout) {
553 
554         CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
555         try {
556 
557             HttpPost httpPost = new HttpPost(url);
558             httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
559             if (!StringUtils.isEmpty(params)) {
560                 httpPost.setEntity(new StringEntity(params, "UTF-8"));
561             }
562             if (headers != null && headers.size() > 0) {
563                 for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
564                     String key = iter.next();
565                     httpPost.setHeader(key, headers.get(key));
566                 }
567             }
568             timeout = timeout != null ? timeout : default_timeout;
569             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
570                     .build();// 设置请求和传输超时时间
571             httpPost.setConfig(requestConfig);
572 
573             CloseableHttpResponse response = httpclient.execute(httpPost);
574             HttpEntity entity = response.getEntity();
575             // 方法一:
576             try {
577                 if (entity != null) {
578                     StringBuilder sb = new StringBuilder();
579                     String line = null;
580                     InputStream inputStream = entity.getContent();
581                     try {
582                         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
583                         while ((line = bufferedReader.readLine()) != null) {
584                             sb.append(line);
585                         }
586                     } finally {
587                         inputStream.close();
588                     }
589                     return sb.toString();
590                 }
591             } finally {
592                 response.close();
593             }
594             // 方法二:
595             /*
596              * try { if (entity != null) return EntityUtils.toString(entity); } finally { if
597              * (entity != null) EntityUtils.consume(entity); response.close(); }
598              */
599         } catch (ParseException e) {
600             log.error("发送HTTP请求时出现异常:" + e);
601             e.printStackTrace(System.out);
602         } catch (IOException e) {
603             log.error("发送HTTP请求时出现异常:" + e);
604             e.printStackTrace(System.out);
605         } catch (Exception e) {
606             log.error("发送HTTP请求时出现异常:" + e);
607             e.printStackTrace(System.out);
608         } finally {
609         }
610         return null;
611     }
612     
613     public static String putBodyJson(String url, String params, Map<String, String> headers, Integer timeout) {
614 
615         CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
616         try {
617 
618             HttpPut httpPost = new HttpPut(url);
619             httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
620             if (!StringUtils.isEmpty(params)) {
621                 httpPost.setEntity(new StringEntity(params, "UTF-8"));
622             }
623             if (headers != null && headers.size() > 0) {
624                 for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
625                     String key = iter.next();
626                     httpPost.setHeader(key, headers.get(key));
627                 }
628             }
629             timeout = timeout != null ? timeout : default_timeout;
630             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
631                     .build();// 设置请求和传输超时时间
632             httpPost.setConfig(requestConfig);
633 
634             CloseableHttpResponse response = httpclient.execute(httpPost);
635             HttpEntity entity = response.getEntity();
636             // 方法一:
637             try {
638                 if (entity != null) {
639                     StringBuilder sb = new StringBuilder();
640                     String line = null;
641                     InputStream inputStream = entity.getContent();
642                     try {
643                         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
644                         while ((line = bufferedReader.readLine()) != null) {
645                             sb.append(line);
646                         }
647                     } finally {
648                         inputStream.close();
649                     }
650                     return sb.toString();
651                 }
652             } finally {
653                 response.close();
654             }
655             // 方法二:
656             /*
657              * try { if (entity != null) return EntityUtils.toString(entity); } finally { if
658              * (entity != null) EntityUtils.consume(entity); response.close(); }
659              */
660         } catch (ParseException e) {
661             log.error("发送HTTP请求时出现异常:" + e);
662             e.printStackTrace(System.out);
663         } catch (IOException e) {
664             log.error("发送HTTP请求时出现异常:" + e);
665             e.printStackTrace(System.out);
666         } catch (Exception e) {
667             log.error("发送HTTP请求时出现异常:" + e);
668             e.printStackTrace(System.out);
669         } finally {
670         }
671         return null;
672     }
673 }

 

posted @ 2019-08-28 15:46  __Ant  阅读(758)  评论(0编辑  收藏  举报