OkHttp 处理Https问题

Posted 吹着空调哼着歌

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OkHttp 处理Https问题相关的知识,希望对你有一定的参考价值。

onFailure: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
在之前接入php接口时是http没有任何问题完美跑通
但在正式环境下域名切换到https下就会出现一个异常
onFailure: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
我以为是后台配置的ssl问题   我在项目中assets下也配置了ssl并在OkHttp下设置了路径
public static SSLSocketFactory getSslSocketFactory() 
        SSLContext sslContext = null;
        try 
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            Certificate ca;
            InputStream certificates = null;
            try 
                certificates = MyApplication.APP.getAssets().open("cmzk.cer");
                ca = certificateFactory.generateCertificate(certificates);
             finally 
                if (certificates != null) 
                    certificates.close();
                
            
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, tmf.getTrustManagers(), null);
         catch (Exception e) 
            e.printStackTrace();
        
        return sslContext != null ? sslContext.getSocketFactory() : null;


    

在创建OkHttp实例时配置ssl证书,发现并没任何用还是会抛出ssl异常

okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(CON_TIME, TimeUnit.SECONDS)
                .readTimeout(READ_TIME, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIME, TimeUnit.SECONDS)
                .addNetworkInterceptor(internateInttercepter)
                .addInterceptor(appInterceptor)
                .sslSocketFactory(getSslSocketFactory())//设置https证书
                .hostnameVerifier(new HostnameVerifier() 
                    @Override
                    public boolean verify(String hostname, SSLSession session) 
                        return true;
                )
                .cache(cache)
                .build();
到这里就很神奇了?
我没有配置ssl也会异常,我配置了还会异常  ****(口吐芬芳)
后来发现OkHttp默认验证SSL  那么给他关掉不久好了(想法 idea)
private SSLSocketFactory createSSLSocketFactory() 
        SSLSocketFactory ssfFactory = null;
        try 
            MyTrustManager mMyTrustManager = new MyTrustManager();
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]mMyTrustManager, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
         catch (Exception ignored) 
            ignored.printStackTrace();
        

        return ssfFactory;
    
    //实现X509TrustManager接口
    public static class MyTrustManager 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];
        
    
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(CON_TIME, TimeUnit.SECONDS)
                .readTimeout(READ_TIME, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIME, TimeUnit.SECONDS)
                .addNetworkInterceptor(internateInttercepter)
                .addInterceptor(appInterceptor)
//                .sslSocketFactory(getSslSocketFactory())//设置https证书
                .sslSocketFactory(createSSLSocketFactory())//忽略ssl验证
                .hostnameVerifier(new HostnameVerifier() 
                    @Override
                    public boolean verify(String hostname, SSLSession session) 
                        return true;
                    
                )
                .cache(cache)
                .build();
测试完美跑通!
*注意 Retrofit也是一样哦

针对https的处理,目前主要有两种方式:
客户端默认信任全部证书
对自签名网址进行证书的单独处理

以上是关于OkHttp 处理Https问题的主要内容,如果未能解决你的问题,请参考以下文章

Android开发学习之OkHttp框架

Android开发学习之OkHttp框架

更改手机系统的User-Agent & okhttp

使用 OkHttp 3 自动处理 cookie

Android上使用retrofit+okhttp时token失效的处理方案

在 Okhttp 中处理身份验证