这是关于证书验证问题,我觉得有必要单独写一篇。
1.HTTP改为HTTPS
参考网址:
异常:javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
说明:因为Https的安全性,保证信息安全,对于我们程序员而言就是随之而来的适配问题。现在比较火的网络请求框架RxJava + Retrofit + OkHttp ,在我们进行网络请求时,需要区分链接是http还是https,便于进行https的校验。
异常说明:由于项目的https.bks证书不是正规的CA签发的证书,而是二级代理商等签发的证书,验证不通过造成的!!!
解决方案:
1.获取正规合法的https证书,让后台上传或者存在assets中,进行应用验证,这是最根本的解决办法!
2.忽略https的证书校验;具体做法:需要在获取sslParams时,修改并自定义TrustManager为
trustAllCerts
//在继承的Application类里面onCreat()方法中调用该方法忽略https的证书校验
public static void handleSSLHandshake() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
SSLContext sc = SSLContext.getInstance("TLS");
// trustAllCerts信任所有的证书
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception ignored) {
}
}
异常:javax.net.ssl.SSLException: hostname in certificate didn't match
参考网址:https://blog.csdn.net/qq_18704911/article/details/103965516
原因: 网站使用https服务器,请求的时候遇到证书验证错误。
解决:添加 SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
httpResponse = new DefaultHttpClient().execute(httpPost);
2.ws://改为wss://
异常:Trust anchor for certification path not found.
说明:webSocket中的ws://改为wss://说明是有证书验证的,so
//忽略https的证书校验
private void webSocketWSS(){
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}, new SecureRandom());
SSLSocketFactory factory = sslContext.getSocketFactory();
webSocketClient.setSocket(factory.createSocket());
} catch (Exception e) {
e.printStackTrace();
}
}
此方法需要在WebSocketClient.connect();之前调用,webSocketClient初始化之后调用即可