Android 问题解决:Caused by: java.security.cert.CertificateException

今天在调试Android 程序中,使用Https 协议访问server失败,出现
Caused by: java.security.cert.CertificateException的错误提示,具体的logcat 打印的出错信息如下:

11-28 17:00:30.546: W/System.err(6562): Caused by: java.security.cert.CertificateException: com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: current time: Mon Nov 28 17:00:30 格林尼治标准时间+0800 2016, expiration time: Wed Nov 21 07:48:32 格林尼治标准时间+0800 2012
11-28 17:00:30.546: W/System.err(6562):     at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:296)
11-28 17:00:30.546: W/System.err(6562):     at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:197)
11-28 17:00:30.546: W/System.err(6562):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:584)
11-28 17:00:30.546: W/System.err(6562):     at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
11-28 17:00:30.546: W/System.err(6562):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:378)
11-28 17:00:30.546: W/System.err(6562):     ... 13 more

这里的比较明显提示了错误原因: Https 连接时SSL 证书握手认证出现了错误, 那么怎么解决呢?

通过网络各种查找,终于得以解决,在此记录,分享一下经验:

解决办法:忽略证书验证,具体实现如下:

//忽略 https 证书验证  
if (url.getProtocol().toUpperCase().equals("HTTPS")) {  
    trustAllHosts();  
    HttpsURLConnection httpsCont = (HttpsURLConnection) url.openConnection();  
    https.setHostnameVerifier(HttpIgnoreSSL.DO_NOT_VERIFY);  
    connection = httpsCont;  
} else {  
    connection = (HttpURLConnection) url.openConnection();  
} 

// Create a trust manager that does not validate certificate chains, Android use X509 cert
public static void trustAllHosts() 
{      
    TrustManager[] trustAllCerts = new TrustManager[] { 
        new X509TrustManager() {  
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
            return new java.security.cert.X509Certificate[] {};  
        }  

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
    }  

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
        }  
    } 
};  

    // Install the all-trusting trust manager  
    try {  
        SSLContext sc = SSLContext.getInstance("TLS");  
        sc.init(null, trustAllCerts, new java.security.SecureRandom());  
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}

public final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {  
    public boolean verify(String hostname, SSLSession session) {  
        return true;  
    }  
};     

你可能感兴趣的:(Android/JAVA)