我正在尝试使用(retrofit 2.0,okhttp3)进行https调用,我已经包含了ssl证书,并且可以正常使用OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.sslSocketFactory(getSSLConfig()); 但它显示sslSocketFactory(getSSLConfig())已弃用,并提供了其他选项sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)我想更新我的代码并使用新选项而不是不推荐使用的方法
我在网上搜索,但找不到任何很好的引用。如果有人可以提供对此问题的一些很好的引用,将非常有帮助

最佳答案

您需要有效的证书。创建信任任何SSL证书的受信任OkHttpClient。试试下面的代码:

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { trustManager }, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory, trustManager);

更多信息在这里:Now that SSLSocketFactory is deprecated on Android, what would be the best way to handle Client Certificate Authentication?

10-08 15:33