Skip to content

关于Https

liujingxing edited this page Feb 25, 2023 · 4 revisions

关于https,需要你自定义OkHttpClient对象,RxHttp内部默认的OkHttpClient对象如下:

private static OkHttpClient getDefaultOkHttpClient() {                                 
    return new OkHttpClient.Builder().build();                                                                   
}                                                                                      

以上代码在RxHttpPlugins类中可找到

  • 设置可访问所有的https网站
HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
         //其他配置
        .build();
RxHttpPlugins.init(okHttpClient);
  • 设置具体的证书
HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(证书的inputstream, null, null);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager))
         //其他配置
        .build();
RxHttpPlugins.init(okHttpClient);
  • 双向认证
HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(
	证书的inputstream, 
	本地证书的inputstream, 
	本地证书的密码)
OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager))
         //其他配置
        .build();
RxHttpPlugins.init(okHttpClient);

框架中只是提供了几个实现类,你可以自行实现SSLSocketFactory,传入sslSocketFactory即可。

注: HttpsUtils类来源于鸿洋的okhttputils,其中原理请查看Android Https相关完全解析 当OkHttp遇到Https