How to import self-signed SSL certificate to Volley on Android 4.1+(如何在 Android 4.1+ 上将自签名 SSL 证书导入 Volley)
问题描述
我开发了使用 Volley 的 android 应用程序.所有通信都是通过 HTTPS 连接完成的.因为我是在本地环境下测试的,所以我使用Tomcat的自签名证书.
I develop android application which uses Volley. All communication is done via HTTPS connection. Because I test it on local environment, I use self-signed certificates for Tomcat.
以前,我只有 android 2.3 和 3.0 设备.现在我也有了 4.1 和 4.4.
Before, I had only android 2.3 and 3.0 devices. Now I've got also 4.1 and 4.4.
我的实现使用这种方法:http://developer.android.com/training/articles/security-ssl.html(部分未知的证书颁发机构)在 Android 最高 4.1 的设备上,它可以完美运行.带有自定义证书的 SSLSocketFactory 被传递给 Volley:
My implementation uses this approach: http://developer.android.com/training/articles/security-ssl.html (part Unknown certificate authority) On devices with Android up to 4.1 it works perfectly. SSLSocketFactory with custom certificates is passed to Volley:
Volley.newRequestQueue(getApplicationContext(), new HurlStack(null, socketFactory));
但是在 Android 4.1+ 上会发生什么?为什么它不起作用?我也尝试过像这样的 NullX509TrustManager:
But what happens on Android 4.1+? Why it does not work? I tried also with NullX509TrustManager like this:
private static class NullX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
但是还是不行……
推荐答案
我已经用这里提到的解决方案解决了它:
I've resolved it with solution mentioned here:
http://developer.android.com/training/articles/security-ssl.html
主机名验证的常见问题
通过添加自定义主机名验证器,它在 Volley 项目中为我的主机名返回 true 并编辑 HurlStack openConnection 方法:
by adding custom hostname verifier which returns true for my hostname in Volley project and editing HurlStack openConnection method:
if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
((HttpsURLConnection)connection).setHostnameVerifier(new CustomHostnameVerifier());
}
这篇关于如何在 Android 4.1+ 上将自签名 SSL 证书导入 Volley的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!