美文网首页Android&Kotlin网络
okHttp3.0直接访问https javax.net.ssl

okHttp3.0直接访问https javax.net.ssl

作者: 哥哥是欧巴Vitory | 来源:发表于2019-06-23 18:21 被阅读12次

    //okHttp3添加信任所有证书

    public static 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);

            builder.hostnameVerifier(new HostnameVerifier() {

                @Override

                public boolean verify(String hostname, SSLSession session) {

                    return true;

                }

            });

            return builder.build();

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

    初始化的时候替换:

    OkHttpClient okHttpClient = new OkHttpClient();

    为:

    OkHttpClient okHttpClient = getUnsafeOkHttpClient();

    相关文章

      网友评论

        本文标题:okHttp3.0直接访问https javax.net.ssl

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