报错

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

  1. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
  2. at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
  3. at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
  4. at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
  5. at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
  6. at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
  7. at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
  8. at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
  9. at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:730)
  10. at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:705)
  11. at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:295)
  12. at org.jsoup.helper.HttpConnection.get(HttpConnection.java:284)
  13. Caused by: java.io.EOFException: SSL peer shut down incorrectly
  14. at sun.security.ssl.InputRecord.read(Unknown Source)

解决

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

依赖

  1. import javax.net.ssl.*;
  2. import java.security.SecureRandom;
  3. import java.security.cert.CertificateException;
  4. import java.security.cert.X509Certificate;

方法

  1. /** 信任任何站点 */
  2. public static void trustEveryone() {
  3. try {
  4. HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
  5. @Override
  6. public boolean verify(String hostname, SSLSession session) {
  7. return true;
  8. }
  9. });
  10. SSLContext context = SSLContext.getInstance("TLS");
  11. context.init(null, new X509TrustManager[] { new X509TrustManager() {
  12. @Override
  13. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  14. }
  15. @Override
  16. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  17. }
  18. @Override
  19. public X509Certificate[] getAcceptedIssuers() {
  20. return new X509Certificate[0];
  21. }
  22. } }, new SecureRandom());
  23. HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. }
  27. }

用法

直接在https发生连接代码的前面加入 trustEveryone(); 即可

例如:

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

或者

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

END

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