httpclient4.x 使用连接池发送https请求使用总结

    由于项目中需要用httpclient进行内部服务请求处理,但之前没有是用httpclient中提供的连接池,而是自己封装的一个类似池的结构,一段时间后产生了性能问题,转而尝试通过是用httpclient内部的池进行处理,而且需要支持https的连接。
     所使用的httpclient的版本为4.4.1,一共用到了三个jar:httpclient-4.4.1.jar、httpclient-cache-4.4.1.jar、httpcore-4.4.1.jar。
    所使用的连接池管理器的类为PoolingHttpClientConnectionManager,但httpclient部分参数,包括池的大小,最大路由,缓存,超时这些参数还未做深入研究;
     上代码:
      
  初始化代码:
     public void init()
 {
   try {
   //需要通过以下代码声明对https连接支持
   SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
                   new TrustSelfSignedStrategy())
           .build();
   HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
   SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
           sslcontext,hostnameVerifier);
   Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
           .register("http", PlainConnectionSocketFactory.getSocketFactory())
           .register("https", sslsf)
           .build();
   //初始化连接管理器
   poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
   // Increase max total connection to 200
   poolConnManager.setMaxTotal(maxTotalPool);
   // Increase default max connection per route to 20
   poolConnManager.setDefaultMaxPerRoute(maxConPerRoute);
  } catch (KeyManagementException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (KeyStoreException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
//获取连接
 public CloseableHttpClient getConnection()
 {
      CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(poolConnManager).build(); 
      return httpClient;
 }
//发送请求 url为请求url,jsonstr为请求参数
public String post(String url, String jsonStr)
 {
  String returnStr = null;
  //参数检测
  if(url==null||"".equals(url))
  {
   return returnStr;
  }
  try {
   HttpPost httpPost = new HttpPost(url);
   List <NameValuePair> nvps = new ArrayList <NameValuePair>();
   //设置post参数对
   nvps.add(new BasicNameValuePair("jsonstr", jsonStr));
   //设置编码,如果包含中文,一定要进行设置,否则按照系统默认字符集进行转码会出现乱码
   httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
   CloseableHttpResponse response = client.execute(httpPost);
   //获取响应状态码
   int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity,"utf-8") : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  //相应返回值
  return returnStr;
 }
 

你可能感兴趣的:(httpclient)