场景
自签的SSL证书不受信任,可通过将该证书添加至JDK密钥库,jdk信任自签证书,如果这种方法行不通,可尝试该方式
使用代码
public OkHttpClient getUnsafeOkHttpClient() { try { final TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) { }
@Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) { }
@Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } }; final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.sslSocketFactory(sslSocketFactory,(X509TrustManager)(trustAllCerts[0])); builder.hostnameVerifier(new HostnameVerifier() { String[]ssls = {}; @Override public boolean verify(String hostname, SSLSession session) { if (TextUtils.isEmpty(hostname)) { return false; } return !Arrays.asList(ssls).contains(hostname); } });
OkHttpClient okHttpClient = builder.connectTimeout(10, TimeUnit.MINUTES). writeTimeout(10, TimeUnit.MINUTES).readTimeout(10, TimeUnit.MINUTES).retryOnConnectionFailure(true).build(); return okHttpClient; } catch (Exception e) { throw new RuntimeException(e); } }
|
使用方法
OkHttpClient okHttpClient = new OkHttpClient();
OkHttpClient okHttpClient = new Test().getUnsafeOkHttpClient();
|
注:代码来自互联网,稍做修改,侵告知