java使用jsoup时绕过https证书验证

java 代码

  1. 增加一个工具类
  2. 在jsoup获取之前调用此方法
//your code
SSLHelper.init();
Connection connect = Jsoup.connect(url).userAgent(USER_AGENT);
connect.header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
connect.header("Accept-Encoding", "gzip, deflate, sdch");
connect.header("Accept-Language", "zh-CN,zh;q=0.8");
connect.timeout(3000);
connect.ignoreHttpErrors(true);
Document doc = connect.get();
package com.bookmark.analysis.common.util;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class SSLHelper {
    public static String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 5.0)";
    static public void init() {
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[]{new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyManagementException e) {
        }
    }
}

参考资料

https://*.com/questions/40742380/how-to-resolve-jsoup-error-unable-to-find-valid-certification-path-to-requested

上一篇:造成错误“ORA-12547: TNS:lost contact”的常见原因有哪些?


下一篇:URP(一)