OkHttp忽略SSL证书验证

2022-10-31 16:07:58 浏览数 (1)

场景

自签的SSL证书不受信任,可通过将该证书添加至JDK密钥库,jdk信任自签证书,如果这种方法行不通,可尝试该方式

使用代码

代码语言:javascript复制
    /**
     * Created with IDEA
     * Author: www.itze.cn
     * Date: 2021-02-24
     * Email:gitlab@111.com
     * okhttp忽略所有SSL证书认证
     * @return
     */
    public OkHttpClient getUnsafeOkHttpClient() {
        try {
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory,(X509TrustManager)(trustAllCerts[0]));
            builder.hostnameVerifier(new HostnameVerifier() {
                //这里存放不需要忽略SSL证书的域名,为空即忽略所有证书
                String[]ssls = {};
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    if (TextUtils.isEmpty(hostname)) {
                        return false;
                    }
                    return !Arrays.asList(ssls).contains(hostname);
                }
            });

            OkHttpClient okHttpClient = builder.connectTimeout(10, TimeUnit.MINUTES).
                writeTimeout(10, TimeUnit.MINUTES).readTimeout(10, TimeUnit.MINUTES).retryOnConnectionFailure(true).build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

使用方法

代码语言:javascript复制
//将原来的
OkHttpClient okHttpClient = new OkHttpClient();
//替换为
OkHttpClient okHttpClient = new Test().getUnsafeOkHttpClient();  //Test为类名,若为静态方法直接类名.方法名调用即可

注:代码来自互联网,稍做修改,侵告知

0 人点赞