private SSLContext createSSLContext() { SSLContext localSSLContext = null; try { // 创建一个证书库,并将证书导入证书库 KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC"); keyStore.load( mContext.getResources().openRawResource(R.raw.client),//client 是*.pfx文件 CERTFILE_PASSWORD.toCharArray());//CERTFILE_PASSWORD 为你的证书的密码 KeyManagerFactory localKeyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); localKeyManagerFactory.init(keyStore, CERTFILE_PASSWORD.toCharArray()); KeyManager[] arrayOfKeyManager = localKeyManagerFactory .getKeyManagers(); localSSLContext = SSLContext.getInstance("TLS"); localSSLContext.init(arrayOfKeyManager, trustAllCerts, new SecureRandom()); } catch (Exception ex) { ex.printStackTrace(); } return localSSLContext; } public boolean setWebViewSSLCert() { boolean issuc = false;// true 代表验证和设置成功 if (Build.VERSION.SDK_INT >= 14){ return issuc; } try { Field[] arrayOfField = Class.forName( "android.net.http.HttpsConnection").getDeclaredFields(); for (Field localField : arrayOfField) { if (localField.getName().equals("mSslSocketFactory")) {//采用反射的方式修改mSslSocketFactory变量 localField.setAccessible(true); localField.set(null,createSSLContext().getSocketFactory()); issuc = true; break; } } } catch (Exception ex) { ex.printStackTrace(); } return issuc; }
1.2 调用
在webview初始化或者application 等,需要用https认证的地方调用 setWebViewSSLCert方法即可。
下接:http://blog.sina.com.cn/s/blog_618199e60101tgvk.html
转自:http://blog.csdn.net/mingli198611/article/details/9233705
参考:http://www.apkbus.com/forum.php?mod=viewthread&tid=142055