所有 如果你能帮我解决这个问题,我将非常感激。我最近正在开发一个Android应用程序。现在我必须通过Https连接到具有自签名证书的服务器。我需要明确证明证书是自签名的,当然它在我的Android设备上不受信任。 所以我仔细地按照https://developer.android.com/training/articles/security-ssl.html上的步骤进行操作。代码如下:
SSLSocketFactory sslSocketFactory = getSSL(context);
URL url = new URL(address);
HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(sslSocketFactory);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
protected static SSLSocketFactory getSSL(Context context) {
SSLSocketFactory sslSocketFactory = null;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = context.getResources().getAssets().open("softRSAroot.cer");
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
Log.d("maggie", "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();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
sslSocketFactory = sslContext.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
return sslSocketFactory;
}
然后我明白了:
java.util.concurrent.ExecutionException:javax.net.ssl.SSLPeerUnverifiedException:主机名192.168.3.33未经验证: 证书:sha1 / gJuuHkIr9IeY7Q42In3rrg0PvKw = DN:CN = 192.168.3.33,OU = YJY,O = xxx,L = xxx,ST = xxx,C = CN subjectAltNames:[]
ip地址与CN匹配,我正在努力解决这个问题。 感谢您阅读并帮助我。