就两段代码,直接上代码:
protected void onCreate(Bundle savedInstanceState, int layoutResID) {
super.onCreate(savedInstanceState);
setContentView(layoutResID);
javax.net.ssl.SSLPeerUnverifiedException e;
mTitlebar = (TitleBarView) findViewById(R.id.titlebar);
mTitlebar.setListener(this);
AbstractAjaxCallback.setSSF(newSslSocketFactory());//关键代码,实现android-query https自签名验证必须设置ssf
mAQuery = new AQuery(this);
mProgressDlg = new ProgressDialog(this);
mProgressDlg.setIndeterminate(true);
mProgressDlg.setCancelable(true);
mProgressDlg.setInverseBackgroundForced(false);
mProgressDlg.setCanceledOnTouchOutside(true);
mProgressDlg.setTitle(R.string.msg_loading);
}
private SSLSocketFactory newSslSocketFactory() {获取testcert.bks文件的方法:
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");//android好像只支持bks
// KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
// 从资源文件中读取你自己创建的那个包含证书的 keystore 文件
InputStream in = getResources().openRawResource(R.raw.testcert); //这个参数改成你的 keystore 文件名
try {
// 用 keystore 的密码跟证书初始化 trusted
// trusted.load(in, "ipeteipete".toCharArray());
trusted.load(in, "testtest".toCharArray());
} finally {
in.close();
}
// Pass the keystore to the SSLSocketFactory. The factory is responsible
// for the verification of the server certificate.
SSLSocketFactory sf = new SSLSocketFactory(trusted);
// Hostname verification from certificate
// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); // 这个参数可以根据需要调整, 如果对主机名的验证不需要那么严谨, 可以将这个严谨程度调低些.
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
- 首先通过浏览器访问https连接,获取证书保存为test.cer.
- 下载bcprov-jdk15on-146.jar
- 把什么步骤的两个文件拷贝到通一目录下,然后到该目录下执行以下命令:
keytool -importcert -v -trustcacerts -alias test -file test.cer -keystore testcert.bks -storetype BKS -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath ./bcprov-jdk15on-146.jar -storepass testtest
- 把生成的testcert.bks拷贝到过程的raw目录下
参考: