androidOkhttp3信任所有证书设置

Posted 永远不要矫情

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了androidOkhttp3信任所有证书设置相关的知识,希望对你有一定的参考价值。

让okhttp信任所有证书,采用的是忽略https认证,自己构建一个x509认证,默认通过,再传到ssl配置工厂中,再用okhttpclient发送请求的时候就不会再报证书错误

 public OkHttp() 
        client = new OkHttpClient.Builder()
      .sslSocketFactory(MySSLSocketClient.getSSLSocketFactory(),MySSLSocketClient.getX509TrustManager()) // //通过sslSocketFactory方法设置https证书 
        .hostnameVerifier(MySSLSocketClient.getHostnameVerifier())
        .build();
    
package test;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class TestSSLSocketClient 
    //获取SSLSocketFactory
    public static SSLSocketFactory getSSLSocketFactory() 
        try 
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
         catch (Exception e) 
            throw new RuntimeException(e);
        
    

    //获取TrustManager
    private static TrustManager[] getTrustManager() 
        TrustManager[] trustAllCerts = new TrustManager[]
                new X509TrustManager() 
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) 
                    
                    
                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) 
                    

                    @Override
                    public X509Certificate[] getAcceptedIssuers() 
                        return new X509Certificate[];
                    
                
        ;
        return trustAllCerts;
    

    //获取HostnameVerifier,验证主机名
    public static HostnameVerifier getHostnameVerifier() 
        HostnameVerifier hostnameVerifier = (s, sslSession) -> true;
        return hostnameVerifier;
    
   //X509TrustManager:证书信任器管理类
    public static X509TrustManager getX509TrustManager() 
        X509TrustManager x509TrustManager = new 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];
            
        ;
        return x509TrustManager;
    

以上是关于androidOkhttp3信任所有证书设置的主要内容,如果未能解决你的问题,请参考以下文章

androidOkhttp3信任所有证书设置

如何将SSL证书设置成受信任的证书

ios 受信任证书被删了怎么办

如何将浏览器中不受信任的证书手动设置为信任

苹果7plus在那看受信任证书

如何设置的证书被信任的春天RestTemplate