httpclient4.x 使用连接池发送https请求使用总结
初始化代码: 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; }?
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。