我正在开发一款应用。定位 Android 4.4(API级别19),我希望在HTTP交换期间,在HTTPS连接的情况下接受所有证书。这是一个明确的选择,因为我的应用程序类似于扫描仪。
我找到的所有示例都使用了类“ org.apache.http.conn.ssl.SSLSocketFactory ”拥有一个接受SSL上下文和主机名验证程序的构造函数的事实。
问题是API级别19中的“SSLSocketFactory”类的实现不再具有此构造函数版本,我找不到向类“SSLSocketFactory”提供自定义TrustManager的方法。
在Android API级别19中,仍然可以通过HttpClient实现我的目标吗?
答案 0 :(得分:4)
信任SSL工厂:
public class TrustSSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public TrustSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
用法:
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new TrustSSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
return new DefaultHttpClient(ccm, params);
(这是我目前使用的代码。请注意,非常不安全,因此仅用于开发)
我无法记住我从哪里获得此代码,所以我不能相信原作者。