使用此网络库:
由于当前状态是开发,我想使用自签名 SSL 证书
图书馆论坛有一些讨论:
https://github.com/koush/ion/issues/3
Ion ion = Ion.getDefault(c);
ion.configure().createSSLContext("TLS");
ion.getHttpClient().getSSLSocketMiddleware().setSSLContext(sslContext);
ion.getHttpClient().getSSLSocketMiddleware().setTrustManagers(trustManagers);
经过一番研究,我抓住了crt并获得了sslContext和trustmanager,问题是,它仍然返回异常
javax.net.ssl.SSLException
Caused by: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
这是我的尝试:
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = getResources().openRawResource(R.raw.load);
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
//System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
ssl_context = SSLContext.getInstance("TLS");
ssl_context.init(null, tmf.getTrustManagers(), null);
} catch (Exception e) {
Log.d("test1", "A: " + e);
}
Ion.getDefault(this).getHttpClient().getSSLSocketMiddleware().setTrustManagers(tmf.getTrustManagers());
Ion.getDefault(this).getHttpClient().getSSLSocketMiddleware().setSSLContext(ssl_context);
//test SSL
Ion.getDefault(this).with(this)
.load("https://na2b.no-ip.com/dragonair/can_app/api/media_list.php")
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
if (e != null) {
Log.d("test1", "B: " + e);
} else {
Log.d("test1", "result" + result);
}
}
});
请注意异常在 B: 部分,这意味着 trustmanager 和 SSLcontext 应该正确构建,如何解决这个问题?
感谢您的帮助。