解決Jsoup或HttpClient 連 https 報錯:Remote host closed connection during handshake

報錯

主要報錯信息如下:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
java.io.EOFException: SSL peer shut down

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:730)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:705)
    at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:295)
    at org.jsoup.helper.HttpConnection.get(HttpConnection.java:284)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
    at sun.security.ssl.InputRecord.read(Unknown Source)

解決

參考:
https://blog.csdn.net/qq_30831935/article/details/94299220

依賴

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

方法

/** 信任任何站點 */
public static void trustEveryone() {
    try {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    } catch (Exception e) {
         e.printStackTrace();
    }
}

用法

直接在https發生連接代碼的前面加入 trustEveryone(); 即可

例如:

trustEveryone();
Jsoup.connect(url).get();

或者

trustEveryone();
CloseableHttpResponse response = httpclient.execute(httpget);

END

補充:用了這個方法以後,絕大部分情況可以正常,小概率還有可能觸發此報錯,初步猜測和網絡環境也有有一定關係。
用瀏覽器試了下,同一個網絡環境下瀏覽器能正常打開,基本就不會有問題。

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