okGo,Glide 忽略https证书

既然选择了远方,便只顾风雨兼程.
okGo,Glide 忽略https证书_第1张图片
该图片来自网络资源,若有侵权,请留言,我将自行删除

由于项目需求变更,网络协议由之前的http调整为https. 第一次接触https,记录下.

参考相关文档:
https://blog.csdn.net/u014752325/article/details/73185351
https://blog.csdn.net/u014752325/article/details/73217577
https://blog.csdn.net/guolin_blog/article/details/78179422

OkGo 忽略https证书

OkGo 3.0 文档上在application初始化中对OKGO的初始化有一种忽略证书验证的方案:

//方法一:信任所有证书,不安全有风险
HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
//方法二:自定义信任规则,校验服务端证书
HttpsUtils.SSLParams sslParams2 = HttpsUtils.getSslSocketFactory(new SafeTrustManager());
//方法三:使用预埋证书,校验服务端证书(自签名证书)
HttpsUtils.SSLParams sslParams3 = HttpsUtils.getSslSocketFactory(getAssets().open("srca.cer"));
//方法四:使用bks证书和密码管理客户端证书(双向认证),使用预埋证书,校验服务端证书(自签名证书)
HttpsUtils.SSLParams sslParams4 = HttpsUtils.getSslSocketFactory(getAssets().open("xxx.bks"), "123456", getAssets().open("yyy.cer"));
builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
//配置https的域名匹配规则,详细看demo的初始化介绍,不需要就不要加入,使用不当会导致https握手失败
builder.hostnameVerifier(new SafeHostnameVerifier());

我们只需要加上下面两行代码:

//方法一:信任所有证书,不安全有风险
HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);

但是加上以上代码,项目依旧报错.
错误信息:

Hostname xxx.35.67.xxx not verified:
certificate: sha256/WHR2TrgnZ+qSxokE0kDPeWCzlvkJANKiD2EBzPCltfg=DN: CN=1xxx.35.67.xxx,OU=Unknown,O=Unknown,L=Unknown,ST=Unknown,C=Unknown subjectAltNames: []

意思是我们的请求证书和服务器的证书不一致,在OkHttpClient.Builder 中有一个hostnameVerifier函数,接收一个HostnameVerifier对象

public interface HostnameVerifier {
    /**
     * Verify that the host name is an acceptable match with
     * the server's authentication scheme.
     *
     * @param hostname the host name
     * @param session SSLSession used on the connection to host
     * @return true if the host name is acceptable
     */
    public boolean verify(String hostname, SSLSession session);
}

该接口作用应该就是验证证书,成功返回true,反之false.所以我们可以设置验证证书成功返回true.

okGo忽略Https总结

在application初始化OKGo的时忽略证书验证.
第一步:
HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
第二步:
builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                //强行返回true 即验证成功
                return true;
            }
 });

Glide 忽略https证书

由于项目中使用glide加载图片,虽然网络接口通了,但是图片加载失败.
如果我们想要更改Glide的某些默认配置项,那么我们就需要自定义模块,自定义模块功能可以将更改Glide配置,替换Glide组件等操作独立出来,使得我们能轻松地对Glide的各种配置进行自定义,并且又和Glide的图片加载逻辑没有任何交集.
首先我们需要自己定义一个类.并实现GlideModule接口.

public class OkHttpGlideModule implements GlideModule {
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
    }


    @Override
    public void registerComponents(Context context, Glide glide) {
  
    }
}

在OkHttpGlideModule类当中,我们重写了applyOptions()和registerComponents()方法,这两个方法分别就是用来更改Glide和配置以及替换Glide组件的.不过,现在glide还无法识别OkHttpGlideModule,我们需要在清单文件application 节点下声明meta-data 子节点. name为OkHttpGlideModule,注意必须是全路径,value 固定写法 GlideModule.



       .....
    

glide在底层自己维护一套网络相关的框架,如果想要使用glide加载https,我们也要做到信任所有证书.
默认情况下,Glide使用的是基于原生HttpURLConnection进行订制的HTTP通讯组件. 我们可以将HttpURLConnection通讯组件换成OKhttp组件.看一下Glide中目前有哪些组件吧,在Glide类的构造方法当中,如下所示:

public class Glide {

    Glide(Engine engine, MemoryCache memoryCache, BitmapPool bitmapPool, Context context, DecodeFormat decodeFormat) {
        ...

        register(File.class, ParcelFileDescriptor.class, new FileDescriptorFileLoader.Factory());
        register(File.class, InputStream.class, new StreamFileLoader.Factory());
        register(int.class, ParcelFileDescriptor.class, new FileDescriptorResourceLoader.Factory());
        register(int.class, InputStream.class, new StreamResourceLoader.Factory());
        register(Integer.class, ParcelFileDescriptor.class, new FileDescriptorResourceLoader.Factory());
        register(Integer.class, InputStream.class, new StreamResourceLoader.Factory());
        register(String.class, ParcelFileDescriptor.class, new FileDescriptorStringLoader.Factory());
        register(String.class, InputStream.class, new StreamStringLoader.Factory());
        register(Uri.class, ParcelFileDescriptor.class, new FileDescriptorUriLoader.Factory());
        register(Uri.class, InputStream.class, new StreamUriLoader.Factory());
        register(URL.class, InputStream.class, new StreamUrlLoader.Factory());
        register(GlideUrl.class, InputStream.class, new HttpUrlGlideUrlLoader.Factory());
        register(byte[].class, InputStream.class, new StreamByteArrayLoader.Factory());

        ...
    }
}

可以看到,这里都是以调用register()方法的方式来注册一个组件,register()方法中传入的参数表示Glide支持使用哪种参数类型来加载图片,以及如何去处理这种类型的图片加载。比如上述register(GlideUrl.class, InputStream.class, new HttpUrlGlideUrlLoader.Factory()); HttpUrlGlideUrlLoader.Factory() 主要负责网络通讯逻辑, 知道了这点 我们可以在这里解决问题.

创建OkHttpUrlLoader类 其实是按照glide HttpUrlGlideUrlLoader 画瓢.

public class OkHttpUrlLoader implements ModelLoader {
    public static class Factory implements ModelLoaderFactory {
        private static volatile OkHttpClient internalClient;
        private OkHttpClient client;

        private static OkHttpClient getInternalClient() {
            if (internalClient == null) {
                synchronized (Factory.class) {
                    if (internalClient == null) {
                        internalClient = new OkHttpClient();
                    }
                }
            }
            return internalClient;
        }

        public Factory() {
            this(getInternalClient());
        }

        public Factory(OkHttpClient client) {
            this.client = client;
        }

        @Override
        public ModelLoader build(Context context, GenericLoaderFactory factories) {
            return new OkHttpUrlLoader(client);
        }

        @Override
        public void teardown() {
        }
    }

    private final OkHttpClient client;

    public OkHttpUrlLoader(OkHttpClient client) {
        this.client = client;
    }

    @Override
    public DataFetcher getResourceFetcher(GlideUrl model, int width, int height) {
        return new OkHttpStreamFetcher(client, model);
    }
}

接着获取SSLSocketFactory 以及 HostnameVerifier 以便忽略证书

public class SSLSocketClient  {
        //获取这个SSLSocketFactory
        public static SSLSocketFactory getSSLSocketFactory() {
            try {
                SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, getTrustManager(), new SecureRandom());
                return sslContext.getSocketFactory();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        //获取TrustManager
        private static TrustManager[] getTrustManager() {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                        }

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

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };
            return trustAllCerts;
        }

        //获取HostnameVerifier
        public static HostnameVerifier getHostnameVerifier() {
            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            };
            return hostnameVerifier;
        }
}

好了,现在就只差最后一步,将我们刚刚创建的OkHttpUrlLoader注册到Glide当中,将原来的HTTP通讯组件给替换掉,如下所示:

public class OkHttpGlideModule implements GlideModule {
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
    }


    @Override
    public void registerComponents(Context context, Glide glide) {
        OkHttpClient mHttpClient = new OkHttpClient().newBuilder()
                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                .build();
        glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(mHttpClient));
    }
}

glide忽略Https总结

主要是替换Glide组件

 public class OkHttpGlideModule implements GlideModule {
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
    }


      // 替换组件
    @Override
    public void registerComponents(Context context, Glide glide) {
      // 忽略证书
        OkHttpClient mHttpClient = new OkHttpClient().newBuilder()
                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                .build();

        glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(mHttpClient));
    }
}

public class OkHttpUrlLoader implements ModelLoader {
    public static class Factory implements ModelLoaderFactory {
        private static volatile OkHttpClient internalClient;
        private OkHttpClient client;

        private static OkHttpClient getInternalClient() {
            if (internalClient == null) {
                synchronized (Factory.class) {
                    if (internalClient == null) {
                        internalClient = new OkHttpClient();
                    }
                }
            }
            return internalClient;
        }

        public Factory() {
            this(getInternalClient());
        }

        public Factory(OkHttpClient client) {
            this.client = client;
        }

        @Override
        public ModelLoader build(Context context, GenericLoaderFactory factories) {
            return new OkHttpUrlLoader(client);
        }

        @Override
        public void teardown() {
        }
    }

    private final OkHttpClient client;

    public OkHttpUrlLoader(OkHttpClient client) {
        this.client = client;
    }

    @Override
    public DataFetcher getResourceFetcher(GlideUrl model, int width, int height) {
        return new OkHttpStreamFetcher(client, model);
    }
}


public class SSLSocketClient  {
        //获取这个SSLSocketFactory
        public static SSLSocketFactory getSSLSocketFactory() {
            try {
                SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, getTrustManager(), new SecureRandom());
                return sslContext.getSocketFactory();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        //获取TrustManager
        private static TrustManager[] getTrustManager() {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                        }

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

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };
            return trustAllCerts;
        }

        //获取HostnameVerifier
        public static HostnameVerifier getHostnameVerifier() {
            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            };
            return hostnameVerifier;
        }
}

上述三个类可以直接copy到你的项目中,glide 强大之处不仅如此,可以移步郭神
https://blog.csdn.net/sgiceleo/article/details/64440783

你可能感兴趣的:(okGo,Glide 忽略https证书)