我在实现与 Android 的 SSL 连接时遇到了一些麻烦。我的程序在特定的时间间隔内发送数据。为了减少发送的数据量,我想使用 SSL 缓存。有人知道如何使用自签名证书和 SSL 缓存在 Android 中创建 HttpClient 吗?
我想使用 HttpClient 类,我的解决方案如下所示(以 CastException 结尾):
private HttpClient getNewHttpClient(Context context, InputStream sslCertificate) {
SSLSessionCache sslSessionCache = new SSLSessionCache(context);
SSLCertificateSocketFactory socketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(15000, sslSessionCache);
KeyStore keyStore = getSSLKeyStore(sslCertificate);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
socketFactory.setTrustManagers(tmf.getTrustManagers());
HttpParams connectionParameters = new BasicHttpParams();
HttpProtocolParams.setVersion(connectionParameters , HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(connectionParameters , HTTP.UTF_8);
HttpConnectionParams.setStaleCheckingEnabled(connectionParameters , false);
HttpConnectionParams.setConnectionTimeout(connectionParameters , 4 * 1000);
HttpConnectionParams.setSoTimeout(connectionParameters , 5 * 1000);
HttpConnectionParams.setSocketBufferSize(connectionParameters , 8192);
HttpClientParams.setRedirecting(connectionParameters , false);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", (SocketFactory) socketFactory , 443));
ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(connectionParameters, registry);
HttpClient httpClient = new DefaultHttpClient(connectionManager, connectionParameters);
return httpClient;
}
那是向 SchemeRegistry 注册新构建方案时的 CastException
W/System.err(343): java.lang.ClassCastException: org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl cannot be cast to org.apache.http.conn.scheme.SocketFactory