RxJava+Retrofit 搭建网络请求框架

前言

以前一直在简书上写文章,而后本身搭建博客,想了一下,其实更多的精力仍是应该放在学习上面,博客等就是分享本身的所学,一直认为,我若是可以把文章写的很明白了,本身也就掌握的差很少了,其次,不少东西本身也方便查看,加快开发的速度。php

Overview

Retrofit 与 RxJava 完美结合,支持断点下载,上传,支持缓存,自定义绑定生命周期.java

github地址android

效果图

Download

Step 1. Add the JitPack repository to your build file

Add it in your root build.gradle at the end of repositories:git

allprojects {
	repositories {
		...
		maven { url 'https://www.jitpack.io' }
	}
}
复制代码

Step 2. Add the dependency

dependencies {
        implementation 'com.github.JiangHaiYang01:RxHttp-RxJava:0.0.2'
}
复制代码

Usage

基础使用

配置retrifot

rxHttp = RxHttp.Builder()
    .baseUrl("https://www.wanandroid.com")
    .isLog(true)
    .level(HttpLevel.BODY)
    .writeTimeout(10)
    .readTimeout(10)
    .connectTimeout(10)
    .build(this)
复制代码

get 网络请求

private fun getRequest() {
     Log.i(TAG, "get 方法启动 线程 ${Thread.currentThread().name}")
     val data = rxHttp
         .create()
         .addParameter("k", "java")
         .doGet(
             parameter = "wxarticle/chapters/json", tClass = TestBean::class.java,
             listener = object : OnHttpListener<TestBean>() {
                 override fun onSuccess(t: TestBean) {
                     log.text = t.toString()
                 }

                 override fun onError(e: Throwable) {
                     log.text = e.toString()
                 }
             }
         )

     Log.i(TAG, "收到响应 $data thread ${Thread.currentThread().name}")

 }
复制代码

post网络请求

private fun postRequest() {
    val data = rxHttp
        .create()
        .addParameter("title", "123456")
        .addParameter("author", "123456")
        .addParameter("link", "123456")
        .doPost("lg/collect/add/json", TestBean::class.java, object : OnHttpListener<TestBean>() {
            override fun onSuccess(t: TestBean) {
                log.text = t.toString()
            }

            override fun onError(e: Throwable) {
                log.text = e.toString()
            }
        })
}
复制代码

说明github

create 方法建立一个请求 使用 addParameter 添加请求参数 使用 addHeard 添加请求头 使用 bindEvent 绑定生命周期 使用 addFile 添加上传的文件(在上传时候使用才有效)express

断点下载

  • 启动下载
rxHttp.create().doDownLoad(info.taskId, info.url, getBasePath(this), info.saveName, this)
复制代码

接口返回apache

interface DownLoadProgressListener {
    /**
     * 下载进度
     *
     * @param key url
     * @param progress  进度
     * @param read  读取
     * @param count 总共长度
     * @param done  是否完成
     */
    fun onUpdate(
        key: String,
        progress: Int,
        read: Long,
        count: Long,
        done: Boolean
    )
}


interface OnDownLoadListener : DownLoadProgressListener {


    //等待下载
    fun onDownLoadPrepare(key: String)

    //进度
    fun onDownLoadProgress(key: String, progress: Int)

    //下载失败
    fun onDownLoadError(key: String, throwable: Throwable)

    //下载成功
    fun onDownLoadSuccess(key: String, path: String)

    //下载暂停
    fun onDownLoadPause(key: String)

    //下载取消
    fun onDownLoadCancel(key: String)
}

复制代码
  • 取消某一个下载任务
doDownLoadCancel(key: String)
复制代码
  • 暂停某一个下载任务
doDownLoadPause(key: String)
复制代码
  • 取消所有任务
doDownLoadCancelAll
复制代码
  • 暂停所有任务
doDownLoadPauseAll
复制代码

上传

  • 启动上传任务
private fun startUploadSuspend(info: UpLoadInfo) {
    rxHttp.create()
        .addFile("uploaded_file", File(info.path))
        .addHeard("heard", "1")
        .addParameter("parameter", "2")
        .doUpload(
            info.taskId,
            "http://t.xinhuo.com/index.php/Api/Pic/uploadPic",
            TestBean::class.java,
            this
        )
}
复制代码
  • 取消某一个上传任务
doUpLoadCancel(tag:String)
复制代码

加入其余自定义的解析器

项目自己 加入了解析器json

client.addConverterFactory(GsonConverterFactory.create())             // json 解析器
client.addCallAdapterFactory(RxJava2CallAdapterFactory.create())      // 支持RxJava
复制代码

若是想支持其余解析器也是能够的api

在 build RxHttp 的时候 使用 addBuilderClientListener 添加解析器缓存

eg:

rxHttp = RxHttp.Builder()
           .baseUrl("https://www.wanandroid.com")
           .isLog(true)
           .level(HttpLevel.BODY)
           .writeTimeout(10)
           .readTimeout(10)
           .connectTimeout(10)
           .addBuilderClientListener(object : OnBuildClientListener {
                   override fun addBuildClient(): MutableSet<Any> {
                       return mutableSetOf(GsonConverterFactory.create(),RxJava2CallAdapterFactory.create())
                   }
               })
           .build(this)
复制代码

是否显示日志打印 && 日志级别

···
.isLog(true)
.level(HttpLevel.BODY)
···
复制代码

保存网络请求的log

有时候 在调试的时候可能须要将 网络请求的log 保存到 本地文件,这里也提供接口,开发者可以使用 addLogListener 自行处理log文件

eg:

rxHttp = RxHttp.Builder()
    .baseUrl("https://www.wanandroid.com")
    .isLog(true)
    .level(HttpLevel.BODY)
    .writeTimeout(10)
    .readTimeout(10)
    .addLogListener(this)
    .connectTimeout(10)
    .build(this)
复制代码

2020-06-04-15-32-48-1591255968

有时候可能不须要那么多的日志 可使用 addLogFilter自定添加过滤器

eg:

rxHttp = RxHttp.Builder()
            .baseUrl("https://www.wanandroid.com")
            .isLog(true)
            .level(HttpLevel.BODY)
            .writeTimeout(10)
            .readTimeout(10)
            .addLogFilter(object :OnLogFilterListener{
                override fun filter(message: String): Boolean {
                    if(message.contains("adb")){
                        return true
                    }
                    return false
                }
            })
            .connectTimeout(10)
            .build(this)
复制代码

注意 上传和下载的日志已通过滤了,是不会显示上传和下载的日志的,这里主要是防止 @Steam 注解失效

网络cache

在构建 RxHttp 的时候 使用 cacheType 方法,构建缓存策略

提供 4中缓存策略,默认是没有网络缓存的

enum class CacheType {
    //不加入缓存的逻辑
    NONE,

    //有网时:每次都请求实时数据; 无网时:无限时请求有网请求好的数据;
    HAS_NETWORK_NOCACHE_AND_NO_NETWORK_NO_TIME,

    //有网时:特定时间以后请求数据; 无网时:无限时请求有网请求好的数据;
    HAS_NETWORK_CACHE_TIME_AND_NO_NETWORK_NO_TIME,

    //有网时:每次都请求实时数据; 无网时:特定时间以前请求有网请求好的数据;
    HAS_NETWORK_NOCACHE_AND_NO_NETWORK_HAS_TIME,

    //有网时:特定时间以后请求数据; 无网时:特定时间以前请求有网请求好的数据;
    HAS_NETWORK_CACHE_TIME_AND_NO_NETWORK_HAS_TIME,
}
复制代码

当使用cache 的时候 提供下面api 处理缓存时间等

  • cacheNetWorkTimeOut

有网时:特定时间以后请求数据;(好比:特定时间为20s) 默认20

  • cacheNoNetWorkTimeOut

无网时:特定时间以前请求有网请求好的数据;((好比:特定时间为30天) 默认30 天 单位(秒)

  • cacheSize

缓存大小 默认10M

  • cachePath

缓存位置 默认沙盒目录下 cacheHttp 文件夹

Cookie 拦截器

fun addCookieInterceptor(
            cookieListener: OnCookieListener,
            onCookieInterceptor: OnCookieInterceptor
        )
复制代码

下载安装包

扫码下载

License

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
复制代码

写在最后

更新的话仍是会放在 Github 上面。毕竟 Github 才是最后的王道,

相关文章
相关标签/搜索