您可以使用 HurlStack 来使用不同的 HttpClient 实现。例如,见how to use OkHttp with Volley:
public class OkHttpStack extends HurlStack {
private final OkHttpClient client;
public OkHttpStack() {
this(new OkHttpClient());
}
public OkHttpStack(OkHttpClient client) {
if (client == null) {
throw new NullPointerException("Client must not be null.");
}
this.client = client;
}
@Override protected HttpURLConnection createConnection(URL url) throws IOException {
return client.open(url);
}
}
并与它一起使用
Volley.newRequestQueue(context, new OkHttpStack())
应该很容易从中得出如何使用您的 http 客户端。如果你想使用自己的 SSL 逻辑,你可以从 HurlStack 覆盖这个方法
private static SSLSocketFactory createPinnedSSLCertFactory(Context ctx) {
//create your implementation
}
我真的不知道你到底想在这里做什么,但这是一个加载空密钥库并将其固定到仅 1 个证书的示例(不接受任何其他证书 -> ssl 固定)
private static SSLSocketFactory createPinnedSSLCertFactory(Context ctx) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate myCert = //read certificate in;
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null); //inputstream null creates new keystore
keyStore.setCertificateEntry("mycert", myCert );
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
return context.getSocketFactory();
}
注意:我在使用 Gingerbread (2.3) 创建自己的 SSLFactory 时遇到了问题,更低意味着它不起作用。