上個星期,遇到了加密視頻不能播放的問題,檢查了日志發現如下報錯:
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
最終敲定原因,應該是HTTPS站點的SSL數字證書出錯,導致無法建立網絡連接,無法下載解密文件,也就無法播放加密視頻了。
解決方法無非兩個:
1、保持原有設計,那就是更新證書。
2、證書不能動的 情況下,那就只能通過代碼來忽略掉證書,直接建立連接了。
關鍵代碼如下:
public static void trustAllHosts() { // Create a trust manager that does not validate certificate chains // Android use X509 cert 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(); } }