使Okhttp信任所有https

转载:https://blog.csdn.net/u011943534/article/details/118875655

为了支持HTTPS,采用暴力方案,信任所有的证书和主机

修改构建OkhttpClient的方式,添加sslSocketFactory和hostnameVerifier

 client = new OkHttpClient().newBuilder()
                            .readTimeout(okHttpConfig.getReadTimeout(), TimeUnit.MILLISECONDS)
                            .writeTimeout(okHttpConfig.getWriteTimeout(), TimeUnit.MILLISECONDS)
                            .connectTimeout(okHttpConfig.getConnectTimeout(), TimeUnit.MILLISECONDS)
                            .connectionPool(new ConnectionPool(okHttpConfig.getMaxIdleConnection(), okHttpConfig.getKeepAliveDuration(), TimeUnit.MINUTES))
                            .retryOnConnectionFailure(true)
                            .sslSocketFactory(createSSLSocketFactory(), new TrustAllCerts( ))
                            .hostnameVerifier(new TrustAllHostnameVerifier())
//                            .cache(cache)
                            .build();
 private static class TrustAllCerts 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];
        }
    }

    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return ssfFactory;
    }

就这样可以了,使用之前封装的Okhttp方法,可以访问Https的服务了

posted @ 2023-05-29 21:05  远洪  阅读(800)  评论(0)    收藏  举报