Skip to content

关于Https

liujingxing edited this page May 24, 2020 · 4 revisions

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

private static OkHttpClient getDefaultOkHttpClient() {                                 
    SSLParams sslParams = HttpsUtils.getSslSocketFactory();                            
    return new OkHttpClient.Builder()                                                  
        .connectTimeout(10, TimeUnit.SECONDS)                                          
        .readTimeout(10, TimeUnit.SECONDS)                                             
        .writeTimeout(10, TimeUnit.SECONDS)                                            
        .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager) //添加信任证书 
        .hostnameVerifier((hostname, session) -> true) //忽略host验证                      
        .build();                                                                      
}                                                                                      

以上代码在HttpSender类中可找到

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

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

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