美文网首页
解决Jsoup或HttpClient 连 https 报错:Re

解决Jsoup或HttpClient 连 https 报错:Re

作者: zzzmh | 来源:发表于2019-07-12 14:42 被阅读0次

报错

主要报错信息如下:
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

补充:用了这个方法以后,绝大部分情况可以正常,小概率还有可能触发此报错,初步猜测和网络环境也有有一定关系。
用浏览器试了下,同一个网络环境下浏览器能正常打开,基本就不会有问题。

相关文章

网友评论

      本文标题:解决Jsoup或HttpClient 连 https 报错:Re

      本文链接:https://www.haomeiwen.com/subject/fygekctx.html