OkHttp关于https请求的设置

https请求由于证书验证问题,直接请求一般都会失败.一般是做证书验证处理或者忽略证书验证,这里介绍后者.解决方案从外文文章中看到,这里搬砖一下.希望对大家有帮助

  public 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 null;
                }
            }};

            // 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 okHttpClient = new OkHttpClient();
            okHttpClient.setSslSocketFactory(sslSocketFactory);
            okHttpClient.setHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;

                }
            });

            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


}

由于Retrofit库和Picasso库的网络请求都是基于OkHttp,大家在使用这两个库的时候也可以使用此解决方案,来进行https请求
Picasso库做如下配置即可:

Picasso picasso = new Picasso.Builder(context) .downloader(new OkHttpDownloader(client)) .build();

不过建议大家用如下方方法配置,这样配置后即可像平时那样正常使用Picasso

//设置Picasso
Picasso.setSingletonInstance(new Picasso.Builder(context).
downloader(newOkHttpDownloader(RetrofitUtils.getClient(context)))
.build());

这段代码只可以执行一次,不然会报错,可以放在Application类中oncreate方法中进行设置

你可能感兴趣的:(andorid)