最佳答案
出于测试目的,我试图向 okHttp 客户机添加一个套接字工厂,它在设置代理时信任所有内容。这已经做了很多次,但是我的信任套接字工厂的实现似乎缺少了一些东西:
class TrustEveryoneManager implements X509TrustManager {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { }
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { }
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
OkHttpClient client = new OkHttpClient();
final InetAddress ipAddress = InetAddress.getByName("XX.XXX.XXX.XXX"); // some IP
client.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ipAddress, 8888)));
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = new TrustManager[]{new TrustEveryoneManager()};
sslContext.init(null, trustManagers, null);
client.setSslSocketFactory(sslContext.getSocketFactory);
没有请求被发送出我的应用程序,没有异常被记录,所以它似乎是默默地失败在 okHttp。经过进一步的调查,似乎在 okHttp 的 Connection.upgradeToTls()
中,当强制握手时,会吞噬一个 Exception。我得到的例外是: javax.net.ssl.SSLException: SSL handshake terminated: ssl=0x74b522b0: SSL_ERROR_ZERO_RETURN occurred. You should never see this.
下面的代码生成一个 SSLContext
,它在创建不抛出任何异常的 SSLSocketFactory 时起到了魔力般的作用:
protected SSLContext getTrustingSslContext() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
final SSLContextBuilder trustingSSLContextBuilder = SSLContexts.custom()
.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true; // Accepts any ssl cert whether valid or not.
}
});
return trustingSSLContextBuilder.build();
}
问题是,我正试图从我的应用程序中完全删除所有 Apache HttpClient 依赖项。使用 Apache HttpClient 生成 SSLContext
的底层代码看起来非常简单,但是我显然遗漏了一些东西,因为我无法配置我的 SSLContext
来匹配它。
有没有人能够生成一个 SSLContext 实现,在不使用 Apache HttpClient 的情况下做我想做的事情?