解决Jsoup或HttpClient 连 https 报错:Remote host closed connection during handshake home 编辑时间 2019/07/11 ![](/api/file/getImage?fileId=5d26b29916199b068300341e) ## 报错 主要报错信息如下: `javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake` `java.io.EOFException: SSL peer shut down` ```java 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 依赖 ```java import javax.net.ssl.*; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; ``` 方法 ```java /** 信任任何站点 */ 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();` 即可** 例如: ```java trustEveryone(); Jsoup.connect(url).get(); ``` 或者 ```java trustEveryone(); CloseableHttpResponse response = httpclient.execute(httpget); ``` ## END 补充:用了这个方法以后,绝大部分情况可以正常,小概率还有可能触发此报错,初步猜测和网络环境也有有一定关系。 用浏览器试了下,同一个网络环境下浏览器能正常打开,基本就不会有问题。 送人玫瑰,手留余香 赞赏 Wechat Pay Alipay Linux Deepin 15.10.2 下折腾 Conky Conky-manager Javascript 实现Gzip 压缩字符串