美文网首页
OkHttp的Https认证问题

OkHttp的Https认证问题

作者: Dale_Dawson | 来源:发表于2019-01-11 11:03 被阅读0次

            之前项目在上线前,用的都是http打头的接口地址,产品准备上线,然后全部接口换成https打头的,之前写的okhttp访问出现了问题,经过查询相关资料,okhttp如需访问https,需要做以下操作

    1.新TrustAllcert类实现X509TrustManager接口

    public class TrustAllCerts implements X509TrustManager {  
        @Override    
        public void checkClientTrusted(X509Certificate[] chain, String authType) {}  
    
        @Override    
        public void checkServerTrusted(X509Certificate[] chain, String authType) {}  
    
        @Override    
        public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}    
    }    
    

    2.方法createSSLSocketFactory()调用类TrustAllcert,获取SSLSocketFactory

    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;  
    }  
    

    3.初始化OKHttpClient配置

    OkHttpClient.Builder builder = new OkHttpClient.Builder();  
           builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);  
           builder.sslSocketFactory(createSSLSocketFactory());  
           builder.hostnameVerifier(new HostnameVerifier() {  
               @Override  
               public boolean verify(String hostname, SSLSession session) {  
                   return true;  
               }  
           });  
    

    以上方法即可解决okhttp的https认证问题。

    相关文章

      网友评论

          本文标题:OkHttp的Https认证问题

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