【转】同步的HttpClient使用详解

http://blog.csdn.net/angjunqiang/article/details/54340398

 

 

背景

       服务端以及客户端在开发过程中不可避免的会使用到网络请求,网络请求可以使用Java原生的URLConnection,也可以使用HttpClient。在日常工作中建议大家使用HttpClient。URLConnection需要自己去实现相关的方法,而HttpClient使用起来方便,且提供许多的API。

HttpClient

1、httpClient的特性

 

  • 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)

  • 支持自动转向

  • 支持 HTTPS 协议

  • 支持代理服务器等

2、httpClient版本

       目前httpClient的最新版本为4.5.2,可以通过如下maven获取Jar包,这里以本人常用的4.2.2为例;

[html] view plain copy
 
 print?
  1. <span style="font-size:14px;">   <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->  
  2.      <dependency>  
  3.            <groupId>org.apache.httpcomponents</groupId>  
  4.            <artifactId>httpclient</artifactId>  
  5.           <version>4.2.2</version>  
  6.     </dependency></span>  

 

3、使用方法    

[java] view plain copy
 
 print?
  1. package com.netease.mail.be.appads.web.controller;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.UnsupportedEncodingException;  
  5. import java.net.URI;  
  6. import java.net.URISyntaxException;  
  7. import java.util.List;  
  8.   
  9. import org.apache.commons.lang.StringUtils;  
  10. import org.apache.http.HttpEntity;  
  11. import org.apache.http.HttpResponse;  
  12. import org.apache.http.client.ClientProtocolException;  
  13. import org.apache.http.client.HttpClient;  
  14. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  15. import org.apache.http.client.methods.HttpPost;  
  16. import org.apache.http.entity.StringEntity;  
  17. import org.apache.http.impl.client.DefaultHttpClient;  
  18. import org.apache.http.message.BasicNameValuePair;  
  19. import org.apache.http.protocol.HTTP;  
  20. import org.apache.http.util.EntityUtils;  
  21.   
  22. public class PostSample {  
  23.   
  24.     public String setPost(String url, String reqBody,  
  25.             List<BasicNameValuePair> urlParams) {  
  26.   
  27.         // step1: 构造HttpClient的实例,类似于打开浏览器  
  28.         HttpClient client = new DefaultHttpClient();  
  29.   
  30.         // step2: 创建POST方法的实例,类似于在浏览器地址栏输入url  
  31.         HttpPost postMethod = new HttpPost(url);  
  32.   
  33.         String returnValue = "";  
  34.   
  35.         try {  
  36.             // step3:设置url相关参数  
  37.             if (null != urlParams && !urlParams.isEmpty()) {  
  38.                 String params = EntityUtils.toString(new UrlEncodedFormEntity(  
  39.                         urlParams, HTTP.UTF_8));  
  40.                 postMethod.setURI(new URI(postMethod.getURI().toString() + "?"  
  41.                         + params));  
  42.             }  
  43.   
  44.             // step4:设置请求body参数及头部相关参数  
  45.             if (StringUtils.isNotBlank(reqBody)) {  
  46.                 StringEntity se = new StringEntity(reqBody, "UTF-8");  
  47.                 se.setContentType("application/text; charset=utf-8");  
  48.                 postMethod.setEntity(se);  
  49.             }  
  50.   
  51.             // step5:执行发送请求  
  52.             HttpResponse response = client.execute(postMethod);  
  53.             int statusCode = response.getStatusLine().getStatusCode();  
  54.             if (statusCode == 200) {  
  55.                 // 校验码  
  56.                 HttpEntity he = response.getEntity();  
  57.                 returnValue = new String(EntityUtils.toByteArray(he), "UTF-8");  
  58.                 System.out.println("Bid Request Send Succeed." + returnValue);  
  59.                 return returnValue;  
  60.             } else if (statusCode == 204) {  
  61.                 System.out.println("Bid Request Send Error, No Content");  
  62.             } else {  
  63.                 System.out.println("Error happens,http status code is "  
  64.                         + statusCode + ".");  
  65.             }  
  66.         } catch (UnsupportedEncodingException e) {  
  67.             System.out.println(Thread.currentThread().getName()  
  68.                     + "发送BidRequest请求错误,编码错误:" + e.getMessage());  
  69.         } catch (ClientProtocolException e) {  
  70.             System.out.println(Thread.currentThread().getName()  
  71.                     + "发送BidRequest请求错误,协议错误错误:" + e.getMessage());  
  72.         } catch (IOException e) {  
  73.             System.out.println(Thread.currentThread().getName()  
  74.                     + "发送BidRequest请求错误,网络IO错误:" + e.getMessage());  
  75.         } catch (URISyntaxException e) {  
  76.             System.out.println(Thread.currentThread().getName()  
  77.                     + "发送BidRequest请求错误,URL语法错误:" + e.getMessage());  
  78.         } finally {  
  79.             // 释放连接,很关键  
  80.             postMethod.releaseConnection();  
  81.         }  
  82.         return returnValue;  
  83.     }  
  84. }  

注:此方法可以应付并发量不高的网络请求,但是对于高并发的网络请求,此方法存在很大的缺陷及性能问题。具体原因如下:

 

  •   此方法每次都会new一个httpClient对象及HttpPost对象,new的时候需要申请系统资源会消耗一定的时间;
  •  虽然请求执行完毕后都执行了postMethod.releaseConnection方法去释放连接,但是这只是应用层的释放,而真正的释放端口需等待一段时间, 这个时间由系统决定。所以在高并发的时候,端口不断的被占用达到系统的最大值,导致后面的网络请求会直接抛出 Cannot assign requested address[不能分配端口]的异常],从而不能进行请求。

高并发的网络请求

      在高并发时,需要用到HttpClient的连接池,连接的作用主要是减少创建链接的次数,请求可以复用之前的连接,所以就可以指定一定数量的连接数让连接池去创建,避免了多次创建新的连接并在系统回收连接时不能及时释放端口的情况下达到可用端口的最大值的问题。具体实现如下:

 

[java] view plain copy
 
 print?
  1. package com.netease.mail.be.appads.web.controller;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.UnsupportedEncodingException;  
  5. import java.net.URI;  
  6. import java.net.URISyntaxException;  
  7. import java.nio.charset.Charset;  
  8. import java.security.cert.CertificateException;  
  9. import java.security.cert.X509Certificate;  
  10. import java.util.List;  
  11.   
  12. import javax.net.ssl.SSLContext;  
  13. import javax.net.ssl.TrustManager;  
  14. import javax.net.ssl.X509TrustManager;  
  15.   
  16. import org.apache.commons.lang.StringUtils;  
  17. import org.apache.http.HttpEntity;  
  18. import org.apache.http.HttpResponse;  
  19. import org.apache.http.HttpVersion;  
  20. import org.apache.http.client.ClientProtocolException;  
  21. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  22. import org.apache.http.client.methods.HttpGet;  
  23. import org.apache.http.client.methods.HttpPost;  
  24. import org.apache.http.conn.scheme.PlainSocketFactory;  
  25. import org.apache.http.conn.scheme.Scheme;  
  26. import org.apache.http.conn.scheme.SchemeRegistry;  
  27. import org.apache.http.conn.ssl.SSLSocketFactory;  
  28. import org.apache.http.entity.StringEntity;  
  29. import org.apache.http.impl.client.DefaultHttpClient;  
  30. import org.apache.http.impl.conn.PoolingClientConnectionManager;  
  31. import org.apache.http.message.BasicNameValuePair;  
  32. import org.apache.http.params.BasicHttpParams;  
  33. import org.apache.http.params.CoreConnectionPNames;  
  34. import org.apache.http.params.CoreProtocolPNames;  
  35. import org.apache.http.params.HttpParams;  
  36. import org.apache.http.util.EntityUtils;  
  37. import org.slf4j.Logger;  
  38. import org.slf4j.LoggerFactory;  
  39. import org.springframework.stereotype.Service;  
  40.   
  41. /** 
  42.  * HTTP请求对象,支持post与get方法 
  43.  */  
  44. @Service("httpRequesterService")  
  45. public class HttpClientPoolSample {  
  46.   
  47.     private Logger logger = LoggerFactory.getLogger(HttpClientPoolSample.class);  
  48.   
  49.     private static int socketTimeout = 1000;// 设置等待数据超时时间5秒钟 根据业务调整  
  50.   
  51.     private static int connectTimeout = 2000;// 连接超时  
  52.   
  53.     private static int maxConnNum = 4000;// 连接池最大连接数  
  54.   
  55.     private static int maxPerRoute = 1500;// 每个主机的并发最多只有1500  
  56.   
  57.     private static PoolingClientConnectionManager cm;  
  58.   
  59.     private static HttpParams httpParams;  
  60.   
  61.     private static final String DEFAULT_ENCODING = Charset.defaultCharset()  
  62.             .name();  
  63.   
  64.     static {  
  65.         SchemeRegistry sr = new SchemeRegistry();  
  66.         sr.register(new Scheme("http", 80, PlainSocketFactory  
  67.                 .getSocketFactory()));  
  68.         SSLSocketFactory sslFactory;  
  69.         try {  
  70.             SSLContext sslContext = SSLContext.getInstance("SSL");  
  71.             X509TrustManager tm = new X509TrustManager() {  
  72.                 @Override  
  73.                 public void checkClientTrusted(X509Certificate[] chain,  
  74.                         String authType) throws CertificateException {  
  75.                 }  
  76.   
  77.                 @Override  
  78.                 public void checkServerTrusted(X509Certificate[] chain,  
  79.                         String authType) throws CertificateException {  
  80.                 }  
  81.   
  82.                 @Override  
  83.                 public X509Certificate[] getAcceptedIssuers() {  
  84.                     return null;  
  85.                 }  
  86.             };  
  87.             sslContext.init(null, new TrustManager[] { tm },  
  88.                     new java.security.SecureRandom());  
  89.             sslFactory = new SSLSocketFactory(sslContext,  
  90.                     SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  91.             sr.register(new Scheme("https", 443, sslFactory));  
  92.         } catch (Exception e) {  
  93.             e.printStackTrace();  
  94.         }  
  95.         // 初始化连接池  
  96.         cm = new PoolingClientConnectionManager(sr);  
  97.         cm.setMaxTotal(maxConnNum);  
  98.         cm.setDefaultMaxPerRoute(maxPerRoute);  
  99.         httpParams = new BasicHttpParams();  
  100.         httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,  
  101.                 HttpVersion.HTTP_1_1);  
  102.         httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,  
  103.                 connectTimeout);// 请求超时时间  
  104.         httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,  
  105.                 socketTimeout);// 读取数据超时时间  
  106.         // 如果启用了NoDelay策略,httpclient和站点之间传输数据时将会尽可能及时地将发送缓冲区中的数据发送出去、而不考虑网络带宽的利用率,这个策略适合对实时性要求高的场景  
  107.         httpParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);  
  108.         httpParams.setBooleanParameter(  
  109.                 CoreConnectionPNames.STALE_CONNECTION_CHECK, true);  
  110.     }  
  111.   
  112.     public DefaultHttpClient getHttpClient() {  
  113.         return new DefaultHttpClient(cm, httpParams);  
  114.     }  
  115.   
  116.     public String httpGet(String url, List<BasicNameValuePair> parameters) {  
  117.   
  118.         DefaultHttpClient client = getHttpClient();// 默认会到池中查询可用的连接,如果没有就新建  
  119.         HttpGet getMethod = null;  
  120.         String returnValue = "";  
  121.         try {  
  122.             getMethod = new HttpGet(url);  
  123.   
  124.             if (null != parameters) {  
  125.                 String params = EntityUtils.toString(new UrlEncodedFormEntity(  
  126.                         parameters, DEFAULT_ENCODING));  
  127.                 getMethod.setURI(new URI(getMethod.getURI().toString() + "?"  
  128.                         + params));  
  129.                 logger.debug("httpGet-getUrl:{}", getMethod.getURI());  
  130.             }  
  131.   
  132.             HttpResponse response = client.execute(getMethod);  
  133.             int statusCode = response.getStatusLine().getStatusCode();  
  134.   
  135.             if (statusCode == 200) {  
  136.                 HttpEntity he = response.getEntity();  
  137.                 returnValue = new String(EntityUtils.toByteArray(he),  
  138.                         DEFAULT_ENCODING);  
  139.                 return returnValue;  
  140.             }  
  141.   
  142.         } catch (UnsupportedEncodingException e) {  
  143.             logger.error(Thread.currentThread().getName()  
  144.                     + "httpGet Send Error,Code error:" + e.getMessage());  
  145.         } catch (ClientProtocolException e) {  
  146.             logger.error(Thread.currentThread().getName()  
  147.                     + "httpGet Send Error,Protocol error:" + e.getMessage());  
  148.         } catch (IOException e) {  
  149.             logger.error(Thread.currentThread().getName()  
  150.                     + "httpGet Send Error,IO error:" + e.getMessage());  
  151.         } catch (URISyntaxException e) {  
  152.             logger.error(Thread.currentThread().getName()  
  153.                     + "httpGet Send Error,IO error:" + e.getMessage());  
  154.         } finally {// 释放连接,将连接放回到连接池  
  155.             getMethod.releaseConnection();  
  156.   
  157.         }  
  158.         return returnValue;  
  159.   
  160.     }  
  161.   
  162.     public String httpPost(String url, List<BasicNameValuePair> parameters,  
  163.             String requestBody) {  
  164.   
  165.         DefaultHttpClient client = getHttpClient();// 默认会到池中查询可用的连接,如果没有就新建  
  166.         HttpPost postMethod = null;  
  167.         String returnValue = "";  
  168.         try {  
  169.             postMethod = new HttpPost(url);  
  170.   
  171.             if (null != parameters) {  
  172.                 String params = EntityUtils.toString(new UrlEncodedFormEntity(  
  173.                         parameters, DEFAULT_ENCODING));  
  174.                 postMethod.setURI(new URI(postMethod.getURI().toString() + "?"  
  175.                         + params));  
  176.                 logger.debug("httpPost-getUrl:{}", postMethod.getURI());  
  177.             }  
  178.   
  179.             if (StringUtils.isNotBlank(requestBody)) {  
  180.                 StringEntity se = new StringEntity(requestBody,  
  181.                         DEFAULT_ENCODING);  
  182.                 postMethod.setEntity(se);  
  183.             }  
  184.   
  185.             HttpResponse response = client.execute(postMethod);  
  186.             int statusCode = response.getStatusLine().getStatusCode();  
  187.   
  188.             if (statusCode == 200) {  
  189.                 HttpEntity he = response.getEntity();  
  190.                 returnValue = new String(EntityUtils.toByteArray(he),  
  191.                         DEFAULT_ENCODING);  
  192.                 return returnValue;  
  193.             }  
  194.   
  195.         } catch (UnsupportedEncodingException e) {  
  196.             logger.error(Thread.currentThread().getName()  
  197.                     + "httpPost Send Error,Code error:" + e.getMessage());  
  198.         } catch (ClientProtocolException e) {  
  199.             logger.error(Thread.currentThread().getName()  
  200.                     + "httpPost Send Error,Protocol error:" + e.getMessage());  
  201.         } catch (IOException e) {  
  202.             logger.error(Thread.currentThread().getName()  
  203.                     + "httpPost Send Error,IO error:" + e.getMessage());  
  204.         } catch (URISyntaxException e) {  
  205.             logger.error(Thread.currentThread().getName()  
  206.                     + "httpPost Send Error,IO error:" + e.getMessage());  
  207.         } finally {// 释放连接,将连接放回到连接池  
  208.             postMethod.releaseConnection();  
  209.             // 释放池子中的空闲连接  
  210.             // client.getConnectionManager().closeIdleConnections(30L,  
  211.             // TimeUnit.MILLISECONDS);  
  212.         }  
  213.         return returnValue;  
  214.   
  215.     }  
  216. }   

一些参数的解释:

 

  • socketTimeout:socket超时时间,这个超时时间不是连接的超时时间,而是读取返回值的超时时间,即响应超时时间
  • connectTimeout:请求连接对方的超时时间
  • maxConnNum: 连接池最大并发数。这个设置与应用的并发量有关。比如应用的1s的请求量1000,每个请求需要10ms,则需要的最大并发数为 1000/(1s/10ms)=10,理论上设置的值最好比这个稍大一点点。
  • maxPerRoute:请求后端的最大连接数,比如说后端服务有2台机器,而maxConnNum=10,则maxPerRoute=5

根据如上的配置理论上最多只可能会存在4000个连接,对于空闲的连接连接池会根据默认的设置进行回收,当然也可以在程序中进行回收,回收方法client.getConnectionManager().closeIdleConnections(30000L,TimeUnit.MILLSECONDS)表示这个连接维持30秒的空闲时间后进行回收。如果我们将30000L改为0L,则表示立即进行回收,那就失去了连接池的意义,不建议这样做。

posted @ 2017-07-10 15:28  牧之丨  阅读(1487)  评论(0编辑  收藏  举报