使用httpClient 訪問https請求

package com.hyzs.szcg.doc.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.imageio.stream.FileImageOutputStream;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
@Slf4j
public class TencentApiUtil {
    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;
    private static final int MAX_TIMEOUT = 7000;
    private static final String apiUrl="https://apis.map.qq.com/ws/staticmap/v2/?";
    static {
        // 設置連接池
        connMgr = new PoolingHttpClientConnectionManager();
        // 設置連接池大小
        connMgr.setMaxTotal(100);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // 設置連接超時
        configBuilder.setConnectTimeout(MAX_TIMEOUT);
        // 設置讀取超時
        configBuilder.setSocketTimeout(MAX_TIMEOUT);
        // 設置從連接池獲取連接實例的超時
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
        // 在提交請求之前 測試連接是否可用
        configBuilder.setStaleConnectionCheckEnabled(true);
        requestConfig = configBuilder.build();
    }

    /**
     * GET
     *
     * @date 2019年11月28日
     */
    public static byte[] doGetHttps(String params) {
        // 獲得Http客戶端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 創建Get請求
        HttpGet httpGet = new HttpGet(apiUrl + params);
        // 響應模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 設置連接超時時間(單位毫秒)
                    .setConnectTimeout(7000)
                    // 設置請求超時時間(單位毫秒)
                    .setConnectionRequestTimeout(7000)
                    // socket讀寫超時時間(單位毫秒)
                    .setSocketTimeout(7000)
                    // 設置是否允許重定向(默認爲true)
                    .setRedirectsEnabled(true).build();

            // 將上面的配置信息 運用到這個Get請求裏
            httpGet.setConfig(requestConfig);
            // 由客戶端執行(發送)Get請求
            response = httpClient.execute(httpGet);
            // 從響應模型中獲取響應實體
            HttpEntity responseEntity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return null;
            }
            if (responseEntity != null) {
                String contentType=responseEntity.getContentType().getValue();
                if("image/png".equals(contentType)){
                    return  EntityUtils.toByteArray(responseEntity);
                }else
                {
                    log.error("調用騰訊api="+EntityUtils.toString(responseEntity,"UTF-8"));
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 發送 SSL get 請求(HTTPS),K-V形式
     * @param params 參數map
     * @return
     */
    public static byte[] doGetHttpsSSL(String params) {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
        HttpGet httpGet =  new HttpGet(apiUrl + params);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            return null;
        }
        String contentType=entity.getContentType().getValue();
        try {
            if("image/png".equals(contentType)){
                return  EntityUtils.toByteArray(entity);
            }else
            {
                log.error("調用騰訊api="+EntityUtils.toString(entity,"UTF-8"));
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 創建SSL安全連接
     *
     * @return
     */
    private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
        SSLConnectionSocketFactory sslsf = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                @Override
                public void verify(String host, SSLSocket ssl) throws IOException {
                }

                @Override
                public void verify(String host, X509Certificate cert) throws SSLException {
                }

                @Override
                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                }
            });
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return sslsf;
    }
    //byte數組到圖片
    public static void byte2image(byte[] data,String path){
        if(data.length<3||path.equals("")) return;
        try{
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            System.out.println("Make Picture success,Please find image in " + path);
        } catch(Exception ex) {
            System.out.println("Exception: " + ex);
            ex.printStackTrace();
        }
    }
}
      <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.9</version>
        </dependency>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章