我已经创建了自己的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.SSLSocketFactoryjavax.net.ssl.SSLSocketFactory之间的强制转换类错误。

如何解决呢?

最佳答案

以上代码没有异常。

但是问题是,当尝试使用以下方法在SSLSocketFactory上设置HttpsURLConnection时:

(HttpsURLConnection )connection.setSSLSocketFactory(trusted)


它显示“类型为setSSLSocketFactory(SSLSocketFactory)的方法HttpsURLConnection不适用于参数(SSLSocketFactory)”。

因为这两个软件包中都包含方法setSSLSocketFactory

关于java - 两个包之间的setSSLSocketFactory面临类强制转换错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7160174/

10-09 04:30