'sslSocketFactory(javax.net.ssl.SSLSocketFactory)' is deprecated
具体信息如下:
public OkHttpClient.Builder sslSocketFactory(SSLSocketFactory sslSocketFactory)
Deprecated. SSLSocketFactory does not expose its X509TrustManager, which is a field that OkHttp needs to build a clean certificate chain. This method instead must use reflection to extract the trust manager. Applications should prefer to call sslSocketFactory(SSLSocketFactory, X509TrustManager), which avoids such reflection.
Sets the socket factory used to secure HTTPS connections. If unset, the system default will be used.
Gradle: com.squareup.okhttp3:okhttp:3.8.0
不推荐使用以下方法
1 |
sslSocketFactory(SSLSocketFactory sslSocketFactory) |
可以更新为:
1 |
sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager) |
具体代码如下:
/**
* 信任所有的证书
*/
public static OkHttpClient getHttpsClient(OkHttpClient okhttpClient) {
//OkHttpClient.Builder okhttpClient = new OkHttpClient().newBuilder();
//信任所有服务器地址
okhttpClient.newBuilder().hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
//设置为true
return true;
}
});
//创建管理器
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(
X509Certificate[] x509Certificates,
String s) throws CertificateException {
}
@Override
public void checkServerTrusted(
X509Certificate[] x509Certificates,
String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
} };
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new SecureRandom());
//为OkHttpClient设置sslSocketFactory
okhttpClient.newBuilder().sslSocketFactory(sslContext.getSocketFactory(), new trustAllManager());
} catch (Exception e) {
e.printStackTrace();
}
return okhttpClient.newBuilder().build();
}
private static class trustAllManager implements X509TrustManager{
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}