美文网首页Android
okhttp3证书解决方式

okhttp3证书解决方式

作者: imkobedroid | 来源:发表于2018-04-20 11:12 被阅读0次

    使用okttp3访问https时不配置证书或者忽略证书会报错:

    java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.  
    

    可以采用两种方式:
    第一种:根据自己的证书服务器来配置,达到一对一的效果,每个商业app都应该有自己的证书设置,这样能保证访问的安全性。
    第二种:在okhttp中设置信任所有证书

    今天介绍第二种,具体方式采用下面的工具类:

    public class RxUtils {
    
    @SuppressLint("TrulyRandom")
    public static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory sSLSocketFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllManager()},
                    new SecureRandom());
            sSLSocketFactory = sc.getSocketFactory();
        } catch (Exception ignored) {
        }
        return sSLSocketFactory;
    }
    
    public static class TrustAllManager implements X509TrustManager {
        @SuppressLint("TrustAllX509TrustManager")
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
    
        @SuppressLint("TrustAllX509TrustManager")
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
    
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }
    
    public static class TrustAllHostnameVerifier implements HostnameVerifier {
        @SuppressLint("BadHostnameVerifier")
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
     }
    }
    

    在okhttp中配置:

    private void initOkHttpClient() {
        if (mOkHttpClient == null) {
            synchronized (this) {
                if (mOkHttpClient == null) {
                    OkHttpClient.Builder builder = new OkHttpClient.Builder();
                    HttpLoggingInterceptor loggingInterceptor =
                            new HttpLoggingInterceptor((message) -> Logger.i(message));
                    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    mOkHttpClient= builder.addInterceptor(loggingInterceptor)
                            .addInterceptor(new DefaultHeaderInterceptor())
                            .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                            .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                            .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                            .sslSocketFactory(RxUtils.createSSLSocketFactory())
                            .hostnameVerifier(new RxUtils.TrustAllHostnameVerifier())
                            .retryOnConnectionFailure(true).build();
                }
            }
        }
    
    }
    

    或者kotlin:

     val client = OkHttpClient.Builder()
                                .addInterceptor(interceptor)
                                .addInterceptor(HeadInterceptor())
                                .retryOnConnectionFailure(true)
                                .connectTimeout(5, TimeUnit.SECONDS)
                                .readTimeout(600, TimeUnit.SECONDS)
                                .writeTimeout(600, TimeUnit.SECONDS)
                                .hostnameVerifier( RxUtils.TrustAllHostnameVerifier())
                                .sslSocketFactory(RxUtils.createSSLSocketFactory(), TrustAllCerts())
                                .retryOnConnectionFailure(true)
                                .build()
    
    
    
    
    class TrustAllCerts : X509TrustManager {
        @SuppressLint("TrustAllX509TrustManager")
        override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
        }
    
        @SuppressLint("TrustAllX509TrustManager")
        override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
        }
    
        override fun getAcceptedIssuers(): Array<X509Certificate?> {
            return arrayOfNulls(0)
        }
    }
    
    

    完成 ! 记住okhttp3以前返回值是有区别的

    相关文章

      网友评论

        本文标题:okhttp3证书解决方式

        本文链接:https://www.haomeiwen.com/subject/eesakftx.html