<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    少年阿賓

    那些青春的歲月

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

    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"表示不開啟證書驗證,只是單存的走https



    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);
    //首先設置全局的標準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();
    // 設置連接池
    httpsClient = HttpClients.custom()
    .setConnectionManager(PoolsManager.getHttpsPoolInstance(socketFactoryRegistry))
    .setConnectionManagerShared(true)
    .setDefaultRequestConfig(requestConfig())
    .setRetryHandler(retryHandler())
    .build();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return httpsClient;
    }

    // 配置請求的超時設置
    //首先設置全局的標準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(){
    //請求重試處理
    HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
    public boolean retryRequest(IOException exception,int executionCount, HttpContext context) {
    if (executionCount >= 5) {// 如果已經重試了5次,就放棄
    return false;
    }
    if (exception instanceof NoHttpResponseException) {// 如果服務器丟掉了連接,那么就重試
    return true;
    }
    if (exception instanceof SSLHandshakeException) {// 不要重試SSL握手異常
    return false;
    }
    if (exception instanceof InterruptedIOException) {// 超時
    return false;
    }
    if (exception instanceof UnknownHostException) {// 目標服務器不可達
    return false;
    }
    if (exception instanceof ConnectTimeoutException) {// 連接被拒絕
    return false;
    }
    if (exception instanceof SSLException) {// ssl握手異常
    return false;
    }

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



    //創建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("請求參數不能為空");
    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("請求參數不能為空");
    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 閱讀(2994) 評論(0)  編輯  收藏 所屬分類: httpClient
    主站蜘蛛池模板: 国产精品亚洲精品观看不卡| 中国内地毛片免费高清| 免费一看一级毛片| 国产在线观a免费观看| 亚洲国产人成在线观看| 亚洲成a人片在线播放| 国产精品免费大片| 亚洲色成人四虎在线观看 | 最新欧洲大片免费在线 | 免费人成再在线观看网站| 亚洲va在线va天堂va四虎| 好男人视频在线观看免费看片| 国产A∨免费精品视频| 亚洲乱码一二三四区国产| 亚洲午夜无码AV毛片久久| 国产精品成人观看视频免费| 又硬又粗又长又爽免费看| 亚洲最大在线观看| 亚洲性在线看高清h片| 无码视频免费一区二三区| 国产久爱免费精品视频| 亚洲午夜福利在线视频| 国产亚洲无线码一区二区| 扒开双腿猛进入爽爽免费视频| 国产无遮挡裸体免费视频在线观看| 亚洲精华国产精华精华液| 亚洲精品自产拍在线观看动漫| 免费播放特黄特色毛片| 久久精品免费一区二区| 13小箩利洗澡无码视频网站免费| 亚洲中文字幕无码久久| 亚洲美女色在线欧洲美女| 亚洲色偷拍另类无码专区| 国产精品免费视频播放器| 97热久久免费频精品99| 国产成人精品无码免费看| 有色视频在线观看免费高清在线直播 | 亚洲色中文字幕在线播放| 亚洲综合网美国十次| 久久久久亚洲AV成人无码网站| 亚洲免费日韩无码系列|