解決HttpClient中HTTPS請(qǐng)求證書域名和請(qǐng)求域名不匹配時(shí)報(bào)錯(cuò)的問題

問題描述

使用HttpClient(版本4.5)進(jìn)行HTTPS請(qǐng)求時(shí),如果目標(biāo)主機(jī)和證書域名不一致時(shí)(比如在測(cè)試或開發(fā)環(huán)境中使用生產(chǎn)的證書或生成證書時(shí)未指定)會(huì)報(bào)錯(cuò):

javax.net.ssl.SSLPeerUnverifiedException: Certificate for <> doesn't match any of the subject alternative names: []
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.verifyHostname(SSLConnectionSocketFactory.java:467)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:397)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:355)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:359)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)

解決辦法

  1. 最好的解決辦法當(dāng)然是搞清楚為什么證書域名不匹配,是不是服務(wù)方給了你一個(gè)假證書。一般情況下,在生產(chǎn)環(huán)境上肯定是一致的,否則你的網(wǎng)站會(huì)被瀏覽器攔截。

  2. 為了開發(fā)調(diào)試順利進(jìn)行,我這里在代碼層面繞過了SSL域名驗(yàn)證:

SSLContext sslcontext = sslContext(keyStorePath, keyStorePassword);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                // 正常的SSL連接會(huì)驗(yàn)證碼所有證書信息
                // .register("https", new SSLConnectionSocketFactory(sslcontext)).build();
                //  只忽略域名驗(yàn)證碼
                .register("https", new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE)).build();

這里的 NoopHostnameVerifier.INSTANCE該主機(jī)名驗(yàn)證器本質(zhì)上會(huì)關(guān)閉主機(jī)名驗(yàn)證。它接受任何有效的和符合目標(biāo)主機(jī)的SSL會(huì)話。

具體的示例代碼:

public static ClientResponse postSSL(String url, String resquestBody, String keyStorePath,
            String keyStorePassword) {
        SSLContext sslcontext = sslContext(keyStorePath, keyStorePassword);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                // 正常的SSL連接會(huì)驗(yàn)證碼所有證書信息
                // .register("https", new SSLConnectionSocketFactory(sslcontext)).build();
                //  只忽略域名驗(yàn)證碼
                .register("https", new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE)).build();
            
        HttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        ClientResponse rsp = null;
        try ( // 創(chuàng)建post方式請(qǐng)求對(duì)象
                CloseableHttpClient client = HttpClients.custom().
                setConnectionManager(connManager).build();) {
            // 設(shè)置連接超時(shí)時(shí)間
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
                    .setConnectTimeout(CONNECT_TIME_OUT).setSocketTimeout(SOCKET_TIME_OUT).build();
            // 創(chuàng)建httpclient對(duì)象
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            // 2 直接是拼接好的key=value或者json字符串等
            httpPost.setEntity(new StringEntity(resquestBody, Const.CHARSET_UTF8));
            // 執(zhí)行請(qǐng)求操作,并拿到結(jié)果
            CloseableHttpResponse response = client.execute(httpPost);
            rsp = new ClientResponse();
            // 獲取響應(yīng)頭
            Header[] rspHeaders = response.getAllHeaders();
            if (ArrayUtils.isNotEmpty(rspHeaders)) {
                Map<String, String> tmp = new HashMap<>();
                for (Header header : rspHeaders) {
                    tmp.put(header.getName(), header.getValue());
                }
            }
            // 響應(yīng)碼
            rsp.setResponseCode(response.getStatusLine().getStatusCode());
            // 獲取結(jié)果實(shí)體
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                /*
                 * 按指定編碼轉(zhuǎn)換結(jié)果實(shí)體為String類型。 如果這行報(bào)錯(cuò) connection
                 * reset,那么有可能是鏈路不通或者post的url過長(zhǎng)。
                 */
                String body = EntityUtils.toString(entity, Const.CHARSET_UTF8);
                rsp.setResponseContent(body);
            }
            // 關(guān)閉流
            EntityUtils.consume(entity);
            // 釋放鏈接
            response.close();
            // 關(guān)閉客戶端
            client.close();
        } catch (Exception e) {
            LOGGER.error("請(qǐng)求出錯(cuò)", e);
        }
        return rsp;
    }

    /**
     * 設(shè)置信任自簽名證書
     * 
     * @param keyStorePath
     *            密鑰庫(kù)路徑
     * @param keyStorepass
     *            密鑰庫(kù)密碼
     * @return
     */
    public static SSLContext sslContext(String keyStorePath, String keyStorepass) {
        SSLContext sc = null;
        FileInputStream instream = null;
        KeyStore trustStore = null;
        try {
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            // 加載密鑰庫(kù)
            instream = new FileInputStream(new File(keyStorePath));
            trustStore.load(instream, keyStorepass.toCharArray());
            // 相信自己的CA和所有自簽名的證書
            sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        } catch (Exception e) {
            LOGGER.error("HTTPS請(qǐng)求初始化SSL異常", e);
        } finally {
            CloseUtil.close(instream);
        }
        return sc;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,924評(píng)論 18 139
  • 目錄 準(zhǔn)備 分析2.1. 三次握手2.2. 創(chuàng)建 HTTP 代理(非必要)2.3. TLS/SSL 握手2.4. ...
    RunAlgorithm閱讀 38,648評(píng)論 12 117
  • 其實(shí),我對(duì)https以前只有一個(gè)大概的了解,最近工作中遇到一個(gè)問題從而將https協(xié)議做了一個(gè)徹底的學(xué)習(xí)和認(rèn)知,下...
    一條魚的星辰大海閱讀 3,494評(píng)論 0 1
  • 一、作用 不使用SSL/TLS的HTTP通信,就是不加密的通信。所有信息明文傳播,帶來了三大風(fēng)險(xiǎn)。 (1)竊聽風(fēng)險(xiǎn)...
    XLsn0w閱讀 10,684評(píng)論 2 44
  • 原文地址 http://blog.csdn.net/u012409247/article/details/4985...
    0fbf551ff6fb閱讀 3,580評(píng)論 0 13