且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败

更新时间:2021-10-24 05:49:23

Java不信任SSL证书。证书可以是自签名的,也可以由其根证书不在Java证书库中的CA(证书颁发机构)签名。

The SSL certificate isn't trusted by Java. The certificate may be self-signed, or it may be signed by a CA (Certificate Authority) whose root certificate is not in the Java certificate store.

添加代码以信任主机提供的证书。在使用URL之前导入证书。

Add the code to trust the certificate provided by host. Import the certificate before consuming the URL.

只需添加以下代码即可信任证书

Just add below code to trust the certificate

TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }
    public void checkClientTrusted(
        java.security.cert.X509Certificate[] certs, String authType) {
    }
    public void checkServerTrusted(
        java.security.cert.X509Certificate[] certs, String authType) {
    }
}};

   try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }

// Add your code below