在項目開發(fā)的工程中氛谜,突然出現(xiàn)了如下錯誤:
javax.net.ssl.SSLHandshakeException: com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: Certificate expired at Thu Mar 15 07:59:59 GMT+08:00 2018 (compared to Thu Mar 15 09:43:41 GMT+08:00 2018)
初次查看網(wǎng)上有很多說是手機系統(tǒng)時間不正確通惫,只要同步時間即可解決。
但是混蔼,當(dāng)服務(wù)那邊做CDN校驗履腋,即使同步了手機時間,也不能從根本上解決這個問題。具體看看錯誤遵湖,就能發(fā)現(xiàn)這個是證書過期悔政,證書不信任。在此延旧,可以使用如下方法進行解決:
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* Created by ncj on 2018/3/15.
*/
public class FakeX509TrustManager implements X509TrustManager {
private static TrustManager[] trustManagers;
private static final X509Certificate[] _AcceptedIssuers = new
X509Certificate[] {};
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
//To change body of implemented methods use File | Settings | File Templates.
}
public boolean isClientTrusted(X509Certificate[] chain) {
return true;
}
public boolean isServerTrusted(X509Certificate[] chain) {
return true;
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return _AcceptedIssuers;
}
public static void allowAllSSL() {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
// TODO Auto-generated method stub
return true;
}
});
SSLContext context = null;
if (trustManagers == null) {
trustManagers = new TrustManager[] { new FakeX509TrustManager() };
}
try {
context = SSLContext.getInstance("TLS");
context.init(null, trustManagers, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
}
使用方法 在網(wǎng)絡(luò)請求之前添加SSL信任:
FakeX509TrustManager.allowAllSSL();
到此結(jié)束谋国。