我已经创建了自己的SSLSocketFactory,如this question中所述
private SSLSocketFactory newSslSocketFactory() {
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");
// Get theraw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
Context context = this.activity;
Resources _resources = context.getResources();
InputStream in = _resources.openRawResource(R.raw.mystore);
try {
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
trusted.load(in, "mypassword".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
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
实际上,我需要在连接之前在
SSLSocketFactory
上设置此HttpsURLConnection
。但是当我尝试通过调用在HttpsURLConnection
上设置它时(HttpsURLConnection )connection.setSSLSocketFactory(trusted);
此时,我面临2个软件包
org.apache.http.conn.ssl.SSLSocketFactory
和javax.net.ssl.SSLSocketFactory
之间的强制转换类错误。如何解决呢?
最佳答案
以上代码没有异常。
但是问题是,当尝试使用以下方法在SSLSocketFactory
上设置HttpsURLConnection
时:
(HttpsURLConnection )connection.setSSLSocketFactory(trusted)
它显示“类型为
setSSLSocketFactory(SSLSocketFactory)
的方法HttpsURLConnection
不适用于参数(SSLSocketFactory)
”。因为这两个软件包中都包含方法
setSSLSocketFactory
。关于java - 两个包之间的setSSLSocketFactory面临类强制转换错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7160174/