少年阿賓

          那些青春的歲月

            BlogJava :: 首頁(yè) :: 聯(lián)系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
          廢話少說(shuō),直接上代碼,以前都是調(diào)用別人寫好的,現(xiàn)在有時(shí)間自己弄下,具體功能如下:
          1、httpClient+http+線程池:
          2、httpClient+https(單向不驗(yàn)證證書)+線程池:

          https在%TOMCAT_HOME%/conf/server.xml里面的配置文件
          <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" 
               maxThreads="150" scheme="https" secure="true" 
               clientAuth="false" keystoreFile="D:/tomcat.keystore" 
               keystorePass="heikaim" sslProtocol="TLS"  executor="tomcatThreadPool"/> 
          其中 clientAuth="false"表示不開啟證書驗(yàn)證,只是單存的走h(yuǎn)ttps



          package com.abin.lee.util;

          import org.apache.commons.collections4.MapUtils;
          import org.apache.commons.lang3.StringUtils;
          import org.apache.http.*;
          import org.apache.http.client.HttpRequestRetryHandler;
          import org.apache.http.client.config.CookieSpecs;
          import org.apache.http.client.config.RequestConfig;
          import org.apache.http.client.entity.UrlEncodedFormEntity;
          import org.apache.http.client.methods.CloseableHttpResponse;
          import org.apache.http.client.methods.HttpGet;
          import org.apache.http.client.methods.HttpPost;
          import org.apache.http.client.protocol.HttpClientContext;
          import org.apache.http.config.Registry;
          import org.apache.http.config.RegistryBuilder;
          import org.apache.http.conn.ConnectTimeoutException;
          import org.apache.http.conn.socket.ConnectionSocketFactory;
          import org.apache.http.conn.socket.PlainConnectionSocketFactory;
          import org.apache.http.conn.ssl.NoopHostnameVerifier;
          import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
          import org.apache.http.entity.StringEntity;
          import org.apache.http.impl.client.CloseableHttpClient;
          import org.apache.http.impl.client.HttpClients;
          import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
          import org.apache.http.message.BasicHeader;
          import org.apache.http.message.BasicNameValuePair;
          import org.apache.http.protocol.HttpContext;
          import org.apache.http.util.EntityUtils;

          import javax.net.ssl.*;
          import java.io.IOException;
          import java.io.InterruptedIOException;
          import java.net.UnknownHostException;
          import java.nio.charset.Charset;
          import java.security.cert.CertificateException;
          import java.security.cert.X509Certificate;
          import java.util.*;

          /**
          * Created with IntelliJ IDEA.
          * User: abin
          * Date: 16-4-18
          * Time: 上午10:24
          * To change this template use File | Settings | File Templates.
          */
          public class HttpClientUtil {
          private static CloseableHttpClient httpsClient = null;
          private static CloseableHttpClient httpClient = null;

          static {
          httpClient = getHttpClient();
          httpsClient = getHttpsClient();
          }

          public static CloseableHttpClient getHttpClient() {
          try {
          httpClient = HttpClients.custom()
          .setConnectionManager(PoolManager.getHttpPoolInstance())
          .setConnectionManagerShared(true)
          .setDefaultRequestConfig(requestConfig())
          .setRetryHandler(retryHandler())
          .build();
          } catch (Exception e) {
          e.printStackTrace();
          }
          return httpClient;
          }


          public static CloseableHttpClient getHttpsClient() {
          try {
          //Secure Protocol implementation.
          SSLContext ctx = SSLContext.getInstance("SSL");
          //Implementation of a trust manager for X509 certificates
          TrustManager x509TrustManager = new X509TrustManager() {
          public void checkClientTrusted(X509Certificate[] xcs,
          String string) throws CertificateException {
          }
          public void checkServerTrusted(X509Certificate[] xcs,
          String string) throws CertificateException {
          }
          public X509Certificate[] getAcceptedIssuers() {
          return null;
          }
          };
          ctx.init(null, new TrustManager[]{x509TrustManager}, null);
          //首先設(shè)置全局的標(biāo)準(zhǔn)cookie策略
          // RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
          ConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(ctx, hostnameVerifier);
          Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
          .register("http", PlainConnectionSocketFactory.INSTANCE)
          .register("https", connectionSocketFactory).build();
          // 設(shè)置連接池
          httpsClient = HttpClients.custom()
          .setConnectionManager(PoolsManager.getHttpsPoolInstance(socketFactoryRegistry))
          .setConnectionManagerShared(true)
          .setDefaultRequestConfig(requestConfig())
          .setRetryHandler(retryHandler())
          .build();
          } catch (Exception e) {
          e.printStackTrace();
          }
          return httpsClient;
          }

          // 配置請(qǐng)求的超時(shí)設(shè)置
          //首先設(shè)置全局的標(biāo)準(zhǔn)cookie策略
          public static RequestConfig requestConfig(){
          RequestConfig requestConfig = RequestConfig.custom()
          .setCookieSpec(CookieSpecs.STANDARD_STRICT)
          .setConnectionRequestTimeout(20000)
          .setConnectTimeout(20000)
          .setSocketTimeout(20000)
          .build();
          return requestConfig;
          }

          public static HttpRequestRetryHandler retryHandler(){
          //請(qǐng)求重試處理
          HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
          public boolean retryRequest(IOException exception,int executionCount, HttpContext context) {
          if (executionCount >= 5) {// 如果已經(jīng)重試了5次,就放棄
          return false;
          }
          if (exception instanceof NoHttpResponseException) {// 如果服務(wù)器丟掉了連接,那么就重試
          return true;
          }
          if (exception instanceof SSLHandshakeException) {// 不要重試SSL握手異常
          return false;
          }
          if (exception instanceof InterruptedIOException) {// 超時(shí)
          return false;
          }
          if (exception instanceof UnknownHostException) {// 目標(biāo)服務(wù)器不可達(dá)
          return false;
          }
          if (exception instanceof ConnectTimeoutException) {// 連接被拒絕
          return false;
          }
          if (exception instanceof SSLException) {// ssl握手異常
          return false;
          }

          HttpClientContext clientContext = HttpClientContext.adapt(context);
          HttpRequest request = clientContext.getRequest();
          // 如果請(qǐng)求是冪等的,就再次嘗試
          if (!(request instanceof HttpEntityEnclosingRequest)) {
          return true;
          }
          return false;
          }
          };
          return httpRequestRetryHandler;
          }



          //創(chuàng)建HostnameVerifier
          //用于解決javax.net.ssl.SSLException: hostname in certificate didn't match: <123.125.97.66> != <123.125.97.241>
          static HostnameVerifier hostnameVerifier = new NoopHostnameVerifier(){
          @Override
          public boolean verify(String s, SSLSession sslSession) {
          return super.verify(s, sslSession);
          }
          };


          public static class PoolManager {
          public static PoolingHttpClientConnectionManager clientConnectionManager = null;
          private static int maxTotal = 200;
          private static int defaultMaxPerRoute = 100;

          private PoolManager(){
          clientConnectionManager.setMaxTotal(maxTotal);
          clientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
          }

          private static class PoolManagerHolder{
          public static PoolManager instance = new PoolManager();
          }

          public static PoolManager getInstance() {
          if(null == clientConnectionManager)
          clientConnectionManager = new PoolingHttpClientConnectionManager();
          return PoolManagerHolder.instance;
          }

          public static PoolingHttpClientConnectionManager getHttpPoolInstance() {
          PoolManager.getInstance();
          // System.out.println("getAvailable=" + clientConnectionManager.getTotalStats().getAvailable());
          // System.out.println("getLeased=" + clientConnectionManager.getTotalStats().getLeased());
          // System.out.println("getMax=" + clientConnectionManager.getTotalStats().getMax());
          // System.out.println("getPending="+clientConnectionManager.getTotalStats().getPending());
          return PoolManager.clientConnectionManager;
          }


          }

          public static class PoolsManager {
          public static PoolingHttpClientConnectionManager clientConnectionManager = null;
          private static int maxTotal = 200;
          private static int defaultMaxPerRoute = 100;

          private PoolsManager(){
          clientConnectionManager.setMaxTotal(maxTotal);
          clientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
          }

          private static class PoolsManagerHolder{
          public static PoolsManager instance = new PoolsManager();
          }

          public static PoolsManager getInstance(Registry<ConnectionSocketFactory> socketFactoryRegistry) {
          if(null == clientConnectionManager)
          clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
          return PoolsManagerHolder.instance;
          }

          public static PoolingHttpClientConnectionManager getHttpsPoolInstance(Registry<ConnectionSocketFactory> socketFactoryRegistry) {
          PoolsManager.getInstance(socketFactoryRegistry);
          // System.out.println("getAvailable=" + clientConnectionManager.getTotalStats().getAvailable());
          // System.out.println("getLeased=" + clientConnectionManager.getTotalStats().getLeased());
          // System.out.println("getMax=" + clientConnectionManager.getTotalStats().getMax());
          // System.out.println("getPending="+clientConnectionManager.getTotalStats().getPending());
          return PoolsManager.clientConnectionManager;
          }

          }

          public static String httpPost(Map<String, String> request, String httpUrl){
          String result = "";
          CloseableHttpClient httpClient = getHttpClient();
          try {
          if(MapUtils.isEmpty(request))
          throw new Exception("請(qǐng)求參數(shù)不能為空");
          HttpPost httpPost = new HttpPost(httpUrl);
          List<NameValuePair> nvps = new ArrayList<NameValuePair>();
          for(Iterator<Map.Entry<String, String>> iterator=request.entrySet().iterator(); iterator.hasNext();){
          Map.Entry<String, String> entry = iterator.next();
          nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
          }
          httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
          System.out.println("Executing request: " + httpPost.getRequestLine());
          CloseableHttpResponse response = httpClient.execute(httpPost);
          result = EntityUtils.toString(response.getEntity());
          System.out.println("Executing response: "+ result);
          } catch (Exception e) {
          throw new RuntimeException(e);
          } finally {
          try {
          httpClient.close();
          } catch (IOException e) {
          e.printStackTrace();
          }
          }
          return result;
          }

          public static String httpPost(String json, String httpUrl, Map<String, String> headers){
          String result = "";
          CloseableHttpClient httpClient = getHttpClient();
          try {
          if(StringUtils.isBlank(json))
          throw new Exception("請(qǐng)求參數(shù)不能為空");
          HttpPost httpPost = new HttpPost(httpUrl);
          for(Iterator<Map.Entry<String, String>> iterator=headers.entrySet().iterator();iterator.hasNext();){
          Map.Entry<String, String> entry = iterator.next();
          Header header = new BasicHeader(entry.getKey(), entry.getValue());
          httpPost.setHeader(header);
          }
          httpPost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
          System.out.println("Executing request: " + httpPost.getRequestLine());
          CloseableHttpResponse response = httpClient.execute(httpPost);
          result = EntityUtils.toString(response.getEntity());
          System.out.println("Executing response: "+ result);
          } catch (Exception e) {
          throw new RuntimeException(e);
          } finally {
          try {
          httpClient.close();
          } catch (IOException e) {
          e.printStackTrace();
          }
          }
          return result;
          }

          public static String httpGet(String httpUrl, Map<String, String> headers) {
          String result = "";
          CloseableHttpClient httpClient = getHttpClient();
          try {
          HttpGet httpGet = new HttpGet(httpUrl);
          System.out.println("Executing request: " + httpGet.getRequestLine());
          for(Iterator<Map.Entry<String, String>> iterator=headers.entrySet().iterator();iterator.hasNext();){
          Map.Entry<String, String> entry = iterator.next();
          Header header = new BasicHeader(entry.getKey(), entry.getValue());
          httpGet.setHeader(header);
          }
          CloseableHttpResponse response = httpClient.execute(httpGet);
          result = EntityUtils.toString(response.getEntity());
          System.out.println("Executing response: "+ result);
          } catch (Exception e) {
          throw new RuntimeException(e);
          } finally {
          try {
          httpClient.close();
          } catch (IOException e) {
          e.printStackTrace();
          }
          }
          return result;
          }


          public static String httpGet(String httpUrl) {
          String result = "";
          CloseableHttpClient httpClient = getHttpClient();
          try {
          HttpGet httpGet = new HttpGet(httpUrl);
          System.out.println("Executing request: " + httpGet.getRequestLine());
          CloseableHttpResponse response = httpClient.execute(httpGet);
          result = EntityUtils.toString(response.getEntity());
          System.out.println("Executing response: "+ result);
          } catch (Exception e) {
          throw new RuntimeException(e);
          } finally {
          try {
          httpClient.close();
          } catch (IOException e) {
          e.printStackTrace();
          }
          }
          return result;
          }





          maven依賴:
            <!--httpclient-->
                  <dependency>
                      <groupId>org.apache.httpcomponents</groupId>
                      <artifactId>httpclient</artifactId>
                      <version>4.5.2</version>
                  </dependency>
                  <dependency>
                      <groupId>org.apache.httpcomponents</groupId>
                      <artifactId>httpcore</artifactId>
                      <version>4.4.4</version>
                  </dependency>
                  <dependency>
                      <groupId>org.apache.httpcomponents</groupId>
                      <artifactId>httpmime</artifactId>
                      <version>4.5.2</version>
                  </dependency>

          <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-collections4</artifactId>
          <version>4.1</version>
          </dependency>
          posted on 2016-04-27 19:04 abin 閱讀(2990) 評(píng)論(0)  編輯  收藏 所屬分類: httpClient
          主站蜘蛛池模板: 香格里拉县| 津市市| 岑巩县| 虹口区| 凭祥市| 怀安县| 隆安县| 繁昌县| 华坪县| 五寨县| 凤冈县| 吉安市| 合川市| 罗城| 阿图什市| 土默特左旗| 周至县| 庆阳市| 柞水县| 鹤岗市| 本溪市| 广平县| 鄂托克前旗| 扎兰屯市| 集贤县| 德清县| 定西市| 广安市| 新化县| 唐海县| 江川县| 甘孜县| 承德市| 遂宁市| 宜都市| 白河县| 河北区| 清远市| 宜良县| 黄龙县| 沛县|