OkHttp报错javax.net.ssl.SSLHandshakeException: Handshake failed

背景

今天学习了一下OkHttp,在使用OkHttp调用https接口的时候,报了SSLHandshakeException的异常,看了网上的资料,主要是服务器端使用了未被信任的证书,然后我就在寻找一种简单快速的解决方案。鸿洋老师在博客里详细阐述了OkHttp访问https的问题,在这里我就不做过多阐述了。

现在给大家贴出我的解决方案

OKHttp信任所有证书

private static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

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

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final 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;
                }
            });

            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

这种方式是最简单快捷的一种解决方案,所以肯定会有它的弊端,从方法名我们可以看出来这是一种https不安全的解决方案,如果你想要一种临时的解决方案,这种方式确实是一种不错的选择。

你可能感兴趣的:(Android)