Retrofit网络加载库二次封装支持RxJava与Flow-HttpUtils

HttpUtils是Retrofit网络加载库二次封装支持RxJava与Flow,包含网络加载动画、activity销毁自动取消请求、网络缓存、公共参数、RSA+AES加密等
GitHub仓库地址

引入

gradle

allprojects {repositories {maven { url 'https://jitpack.io' }}
}implementation 'com.github.DL-ZhangTeng:HttpUtils:2.0.0'//库所使用的三方implementation 'androidx.lifecycle:lifecycle-common:2.4.0'implementation 'androidx.lifecycle:lifecycle-runtime:2.4.0'implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"implementation 'com.squareup.retrofit2:retrofit:2.9.0'implementation 'com.squareup.retrofit2:converter-gson:2.9.0'implementation 'com.squareup.retrofit2:converter-scalars:2.8.1'implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2'implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'//如果不需要rxjava不用导入implementation 'io.reactivex.rxjava2:rxjava:2.2.21'implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'//noinspection GradleDynamicVersionimplementation 'com.github.DL-ZhangTeng:Utils:2.0.+'

属性

属性名 描述
setBaseUrl ConfigGlobalHttpUtils()全局的BaseUrl;ConfigSingleInstance()单独设置BaseUrl
addCallAdapterFactory 设置CallAdapter.Factory,默认FlowCallAdapterFactory.create()、CoroutineCallAdapterFactory.create()、RxJava2CallAdapterFactory.create()
addConverterFactory 设置Converter.Factory,默认GsonConverterFactory.create()
setDns 自定义域名解析
setCache 开启缓存策略
addHeader 全局的单个请求头信息
setHeaders 全局的请求头信息,设置静态请求头:更新请求头时不需要重新设置,对Map元素进行移除添加即可;设置动态请求头:如token等需要根据登录状态实时变化的请求头参数,最小支持api 24
setHttpCallBack 设置网络请求前后回调函数 onHttpResponse:可以先客户端一步拿到每一次Http请求的结果 onHttpRequest:可以在请求服务器之前拿到
setSign 全局验签,appKey与后端匹配即可,具体规则参考:https://blog.csdn.net/duoluo9/article/details/105214983
setEnAndDecryption 全局加解密(AES+RSA)。1、公钥请求路径HttpUrl.get(BuildConfig.HOST + “/getPublicKey”);2、公钥响应结果{“result”: {“publicKey”: “”},“message”: “查询成功!”,“status”: 100}
setCookie 全局持久话cookie,保存本地每次都会携带在header中
addInterceptor 添加拦截器(继承PriorityInterceptor重写getPriority方法自定义顺序,自定义拦截器Priority必须>=10)
addInterceptors 添加拦截器(继承PriorityInterceptor重写getPriority方法自定义顺序,自定义拦截器Priority必须>=10)
addNetworkInterceptor 添加网络拦截器(继承PriorityInterceptor重写getPriority方法自定义顺序,自定义拦截器Priority必须>=10)
addNetworkInterceptors 添加网络拦截器(继承PriorityInterceptor重写getPriority方法自定义顺序,自定义拦截器Priority必须>=10)
setSslSocketFactory 全局ssl证书认证。1、信任所有证书,不安全有风险,setSslSocketFactory();2、使用预埋证书,校验服务端证书(自签名证书),setSslSocketFactory(getAssets().open(“your.cer”));3、使用bks证书和密码管理客户端证书(双向认证),使用预埋证书,校验服务端证书(自签名证书),setSslSocketFactory(getAssets().open(“your.bks”), “123456”, getAssets().open(“your.cer”))
setReadTimeOut 全局超时配置
setWriteTimeOut 全局超时配置
setConnectionTimeOut 全局超时配置
setLog 全局是否打开请求log日志

使用

初始化

class HttpUtilsApplication : Application() {override fun onCreate() {super.onCreate()HttpUtils.init(this)HttpUtils.instance.ConfigGlobalHttpUtils()//全局的BaseUrl.setBaseUrl("https://www.wanandroid.com/")//设置CallAdapter.Factory,默认FlowCallAdapterFactory.create()、CoroutineCallAdapterFactory.create()、RxJava2CallAdapterFactory.create().addCallAdapterFactory(CoroutineCallAdapterFactory.create()).addCallAdapterFactory(FlowCallAdapterFactory.create()).addCallAdapterFactory(RxJava2CallAdapterFactory.create())//设置Converter.Factory,默认GsonConverterFactory.create().addConverterFactory(GsonConverterFactory.create())//设置自定义域名解析//.setDns(HttpDns.getInstance())//开启缓存策略.setCache(true)//全局的单个请求头信息//.addHeader("Authorization", "Bearer ")//全局的静态请求头信息//.setHeaders(headersMap)//全局的请求头信息,需要Android//.setHeaders(headersMap) { headers ->//    headers.apply {//        this["version"] = BuildConfig.VERSION_CODE//        this["os"] = "android"//        val isLogin = BuildConfig.DEBUG//        if (isLogin) {//            this["Authorization"] = "Bearer " + "token"//        } else {//            this.remove("Authorization")//        }//    }//}//全局的动态请求头信息.setHeaders { headers ->headers.apply {this["version"] = BuildConfig.VERSION_CODEthis["os"] = "android"val isLogin = BuildConfig.DEBUGif (isLogin) {this["Authorization"] = "Bearer " + "token"} else {this.remove("Authorization")}}}//.setHttpCallBack(object : CallBack {//    override fun onHttpResponse(//        chain: Interceptor.Chain,//        response: Response//    ): Response {//        //这里可以先客户端一步拿到每一次 Http 请求的结果//        val body: ResponseBody? = response.newBuilder().build().body//        val source = body?.source()//        try {//            source?.request(Long.MAX_VALUE) // Buffer the entire body.//        } catch (e: IOException) {//            e.printStackTrace()//        }//        val buffer: Buffer? = source?.buffer//        var charset: Charset = StandardCharsets.UTF_8//        val contentType: MediaType? = body?.contentType()//        if (contentType != null) {//            charset = contentType.charset(charset)!!//        }//        buffer?.readString(charset).e()//        return response//    }////    override fun onHttpRequest(chain: Interceptor.Chain, request: Request): Request {//        //这里可以在请求服务器之前拿到//        Gson().toJson(request.headers).e()//        val body: RequestBody? = request.body//        try {//            body?.contentLength().toString().e()//        } catch (e: IOException) {//            e.printStackTrace()//        }//        return request//    }//})//全局持久话cookie,保存本地每次都会携带在header中.setCookie(false)//全局ssl证书认证//信任所有证书,不安全有风险.setSslSocketFactory()//使用预埋证书,校验服务端证书(自签名证书)//.setSslSocketFactory(getAssets().open("your.cer"))//使用bks证书和密码管理客户端证书(双向认证),使用预埋证书,校验服务端证书(自签名证书)//.setSslSocketFactory(getAssets().open("your.bks"), "123456", getAssets().open("your.cer"))//全局超时配置.setReadTimeOut(10)//全局超时配置.setWriteTimeOut(10)//全局超时配置.setConnectionTimeOut(10)//全局是否打开请求log日志.setLog(true)}
}

ICallBack回调(更多请求方式请参考MainActivity)

    fun deferredGo_ICallBack() {GlobalScope.launch {HttpUtils.instance.ConfigGlobalHttpUtils().createService(Api::class.java).getHomeListByDeferred(0).deferredGo(object :DeferredCallBack<BaseResult<HomeListBean>>(this@MainActivity) {override fun isHideToast(): Boolean {return true}override fun onFailure(iException: IException?) {Gson().toJson(iException).e("deferredGo_ICallBack")}override fun onSuccess(t: BaseResult<HomeListBean>) {Gson().toJson(t).e("deferredGo_ICallBack")}})}}fun deferredGoIResponse_ICallBack() {GlobalScope.launch {HttpUtils.instance.ConfigGlobalHttpUtils().createService(Api::class.java).getHomeListByDeferred(0).deferredGoIResponse(object :DeferredCallBack<IResponse<HomeListBean>>(this@MainActivity) {override fun isHideToast(): Boolean {return true}override fun onFailure(iException: IException?) {Gson().toJson(iException).e("deferredGoIResponse_ICallBack")}override fun onSuccess(t: IResponse<HomeListBean>) {Gson().toJson(t).e("deferredGoIResponse_ICallBack")}})}}fun flowGo_ICallBack() {GlobalScope.launch {HttpUtils.instance.ConfigGlobalHttpUtils().createService(Api::class.java).getHomeListByFlow(0).flowGo(object :FlowCallBack<BaseResult<HomeListBean>>(this@MainActivity) {override fun isHideToast(): Boolean {return true}override fun onFailure(iException: IException?) {Gson().toJson(iException).e("flowGo_ICallBack")}override fun onSuccess(t: BaseResult<HomeListBean>) {Gson().toJson(t).e("flowGo_ICallBack")}})}}fun flowGoIResponse_ICallBack() {GlobalScope.launch {HttpUtils.instance.ConfigGlobalHttpUtils().createService(Api::class.java).getHomeListByFlow(0).flowGoIResponse(object :FlowCallBack<IResponse<HomeListBean>>(this@MainActivity) {override fun isHideToast(): Boolean {return true}override fun onFailure(iException: IException?) {Gson().toJson(iException).e("flowGoIResponse_ICallBack")}override fun onSuccess(t: IResponse<HomeListBean>) {Gson().toJson(t).e("flowGoIResponse_ICallBack")}})}}fun observableGoCompose() {HttpUtils.instance.ConfigGlobalHttpUtils().createService(Api::class.java).getHomeListByObservable(0)//页面销毁自动取消请求.compose(LifecycleObservableTransformer(this@MainActivity))//自动处理网络加载中动画.compose(ProgressDialogObservableTransformer(this@MainActivity)).subscribe(object : CommonObserver<IResponse<HomeListBean>>() {override fun onFailure(iException: IException?) {Gson().toJson(iException).e("rxjavaGo")}override fun onSuccess(t: IResponse<HomeListBean>) {Gson().toJson(t).e("rxjavaGo")}})}fun observableGoObserver() {HttpUtils.instance.ConfigGlobalHttpUtils().createService(Api::class.java).getHomeListByObservable(0)//页面销毁自动取消请求//自动处理网络加载中动画.subscribe(object : CommonObserver<IResponse<HomeListBean>>(this@MainActivity) {override fun onFailure(iException: IException?) {Gson().toJson(iException).e("rxjavaGo")}override fun onSuccess(t: IResponse<HomeListBean>) {Gson().toJson(t).e("rxjavaGo")}})}//手动取消网络请求
//        HttpUtils.instance.cancelSingleRequest(any);
//        HttpUtils.instance.cancelAllRequest();

混淆

-keep public class com.zhangteng.**.*{ *; }

历史版本

版本 更新 更新时间
v2.0.0 Retrofit网络加载库二次封装支持RxJava与Flow-HttpUtils 2022/9/15 at 0:17

赞赏

如果您喜欢HttpUtils,或感觉HttpUtils帮助到了您,可以点右上角“Star”支持一下,您的支持就是我的动力,谢谢

联系我

邮箱:763263311@qq.com/ztxiaoran@foxmail.com

License

Copyright © [2020] [Swing]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Retrofit网络加载库二次封装支持RxJava与Flow-HttpUtils相关推荐

  1. android快捷开发之Retrofit网络加载框架的简单使用

    大家都知道,安卓最大的特点就是开源化,这自然会产生很多十分好用的第三方API,而基本每一个APP都会与网络操作和缓存处理机制打交道,当然,你可以自己通过HttpUrlConnection再通过返回数据 ...

  2. android 骨架屏刷新动画,ios - 原生骨架屏,网络加载过渡动画的封装

    效果图 闪光灯模式 骨架屏模式 经典动画模式 闪光灯动画.gif 只有骨架屏.gif 经典动画.gif 本项目思维导图 思维导图.JPG 说明 本文将介绍如何将demo集成到你的项目中 均为个人思考, ...

  3. Android图片加载库的封装实战

    重磅更新 2017-02-16 2017-05-09 优化圆形图片加载 更新demo 前言 主流图片加载库的对比 Android-Universal-Image-Loader Picasso Glid ...

  4. Android 二次封装网络加载框架

    Android 二次封装网络加载框架 写在最前面 开发当中,在请求网络的时候,大家或多或少都会使用一些第三方框架,Android-Async-Http. Volley.XUtils.Okhttp.Re ...

  5. 网络加载框架 - Retrofit

    Retrofit是什么? Retrofit其实我们可以理解为OkHttp的加强版,它也是一个网络加载框架.底层是使用OKHttp封装的.准确来说,网络请求的工作本质上是OkHttp完成,而 Retro ...

  6. Google图片加载库Glide的简单封装GlideUtils

    Google图片加载库Glide的简单封装GlideUtils  

  7. LruCache缓存处理及异步加载图片类的封装

    Android中的缓存处理及异步加载图片类的封装   一.缓存介绍: (一).Android中缓存的必要性: 智能手机的缓存管理应用非常的普遍和需要,是提高用户体验的有效手段之一. 1.没有缓存的弊端 ...

  8. android 图片加载库 Glide 的使用介绍

    一:简介 在泰国举行的谷歌开发者论坛上,谷歌为我们介绍了一个名叫 Glide 的图片加载库,作者是bumptech.这个库被广泛的运用在google的开源项目中,包括2014年google I/O大会 ...

  9. android图片加载库Glide

    什么是Glide? Glide是一个加载图片的库,作者是bumptech,它是在泰国举行的google 开发者论坛上google为我们介绍的,这个库被广泛的运用在google的开源项目中. Glide ...

最新文章

  1. onAttach 显示过时的处理方法
  2. 项目福利政策报名 | 项目启动资金、股权投资、住房购房补贴
  3. Spark的stage划分算法源码分析
  4. 兔子运送胡萝卜_我如何建立和运送第一个MVP
  5. this.scrollheight获取textarea的高度是0_【2019年14卷3期】UHF传感器固定角度和加装屏蔽罩对有效高度的影响丨电气工程学报文章推荐...
  6. 不是区块链的特征_《区块链的特征》阅读练习及答案
  7. Delphi 3D Glscene安装
  8. JavaScript时间格式化工具函数
  9. MATLAB必看书籍推荐
  10. ibm r50隐藏分区_网友经历:IBM R50本本内存升级手记
  11. 【spark系列9】spark 的动态分区裁剪上(Dynamic partition pruning)-逻辑计划
  12. centos修改系统可用内存_centos7开启交换内存
  13. AI Earth ——开发者模式案例5:鄱阳湖水体区域识别
  14. 计算机类综合素质测评考什么,综合素质测试考什么内容
  15. nvidia账号、cuDNN的下载账号分享
  16. 优维科技应用CMDB在招商基金的案例分享
  17. cadence之贴片电阻封装绘制
  18. 【移动手游UI设计】笔记
  19. 底量超顶量超级大黑马指标源码_通达信最准的买卖指标,超准短线暴涨指标源码...
  20. 微信电脑版字体模糊(或文字太小)怎么调整

热门文章

  1. 【Word / WPS文字】快速和方便地选择单个一个很小的单元格(而不是选择其中的文字)的技巧
  2. 【面试篇】- 线程和协程的区别是什么?
  3. Swift 实践之绘画
  4. vue项目中 img标签加载失败方法,onerror事件的两种方法
  5. 深度学习环境配置(GPU)
  6. 【背赛笔记 常用写法 模版】Python蓝桥杯备赛笔记记录 【建议收藏!】
  7. Java初学者 定义水仙花类和判断闰年
  8. 路由守卫的简单使用-登录功能
  9. Mysql之limit用法总结
  10. 阿里云域名购买流程以及免费证书的申请(八)