我正在使用com.loopj.android:android-async-http:1.4.9
作为我对服务器的请求。它工作正常,直到我的服务器需要SSL/TLS。所以我需要修改我的AsyncHTTPClient
以在所有网址中使用HTTPS。安装AsyncHttpClient以使用HTTPS
我检查了这个相似的how to make HTTPS calls using AsyncHttpClient?,但没有提供明确的解决方案。由于库本身的这种警告,接受的解决方案也不安全:
警告!这忽略了每个设备上的SSL证书验证,请谨慎使用 。
因此,我继续检查其他解决方案。我结束了以下推荐:https://developer.android.com/training/articles/security-ssl.html。因此,我有一些与此类似:
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// From https://www.washington.edu/itconnect/security/ca/load-der.crt
InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
// Get SocketFactory from our SSLContext
//
// !!!PROBLEM IS HERE!!!
//
javax.net.ssl.SSLSocketFactory socketFactory = context.getSocketFactory();
正如你可以在最后一行看到,它提供了从javax.net.ssl
包的SSLSocketFactory
。然而,AsyncHTTPClient
实例需要
asyncHTTPClient.setSSLSocketFactory(cz.msebera.android.httpclient.conn.ssl.SSLSocketFactory)
编辑:
我的服务器使用的是自签名证书。
您是否找到了一个好的解决方案?我有点失落 –
看起来像@ Prerak的解决方案下面的作品。我也会添加我自己的版本。谢谢。 – user1506104