okHttp javax.net.ssl.SSLHandshakeException的解决办法

安卓线上突然所有接口不能访问,都爆出这个异常 javax.net.ssl.SSLHandshakeException https请求java证书异常
主要原因是前两天公司后台更换java证书问题(以前用的免费证书,后面买了一个新的 更换掉免费的 结果所有接口都不能访问,当时准备让我们重新发版)
解决方法就忽略掉所有证书,不验证证书,但是这样就不安全了。

java代码:

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

kotlin代码:

    private fun getSSLFactory(): SSLSocketFactory {
        //证书忽略添加下面代码(1)打开即可
//         Create a trust manager that does not validate certificate chains
        val trustAllCerts = arrayOf(object : X509TrustManager {
            override fun getAcceptedIssuers(): Array {
                return arrayOf()
            }

            @Throws(CertificateException::class)
            override fun checkClientTrusted(chain: Array, authType: String) {
            }

            @Throws(CertificateException::class)
            override fun checkServerTrusted(chain: Array, authType: String) {
            }
        })

        // Install the all-trusting trust manager
        val sslContext = SSLContext.getInstance("SSL")
        sslContext.init(null, trustAllCerts, java.security.SecureRandom())
        // Create an ssl socket factory with our all-trusting manager
        return sslContext.socketFactory
    }


    fun getOkHttpClient(): OkHttpClient {
        val httpClientBuilder = OkHttpClient.Builder()
        httpClientBuilder.connectTimeout(6, TimeUnit.SECONDS)
        httpClientBuilder.readTimeout(6, TimeUnit.SECONDS)
        httpClientBuilder.writeTimeout(6, TimeUnit.SECONDS)
        httpClientBuilder.addInterceptor(PublicParamsInterceptor())
        httpClientBuilder.addInterceptor(
                CookieInterceptor(if (option == null) false else option!!.isCache,
                        if (option == null) "" else option!!.getUrl()))
        httpClientBuilder.addInterceptor(getHttpLoggingInterceptor())
        //证书忽略
//        httpClientBuilder.sslSocketFactory(getSSLFactory());
//        httpClientBuilder.hostnameVerifier(object : HostnameVerifier {
//            override fun verify(hostname: String, session: SSLSession): Boolean {
//                return true
//            }
//        })
        return httpClientBuilder.build()
    }

    fun  createService(serviceClass: Class, baseUrl: String? = ApiConstants.BASE_URL): T {

        val retrofitBuilder = Retrofit.Builder()
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(baseUrl ?: ApiConstants.BASE_URL)

        return retrofitBuilder
                .client(getOkHttpClient())
                .build()
                .create(serviceClass)
    }

完美解决BUG。

你可能感兴趣的:(网络访问,安卓基础)