java 网络访问框架_RxJava+Retrofit 搭建网络请求框架

前言

之前一直在简书上写文章,然后自己搭建博客,想了一下,其实更多的精力还是应该放在学习上面,博客等就是分享自己的所学,一直认为,我如果能够把文章写的很明白了,自己也就掌握的差不多了,其次,很多东西自己也方便查看,加快开发的速度。

Overview

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

github地址

效果图

b0dad767a65367278ff97c7ec0da8838.png

Download

Step 1. Add the JitPack repository to your build file

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

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() {

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() {

override fun onSuccess(t: TestBean) {

log.text = t.toString()

}

override fun onError(e: Throwable) {

log.text = e.toString()

}

})

}

复制代码说明

create 方法创建一个请求

使用 addParameter 添加请求参数

使用 addHeard 添加请求头

使用 bindEvent 绑定生命周期

使用 addFile 添加上传的文件(在上传时候使用才有效)

断点下载

启动下载

rxHttp.create().doDownLoad(info.taskId, info.url, getBasePath(this), info.saveName, this)

复制代码

接口返回

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)

复制代码

加入其他自定义的解析器

项目本身 加入了解析器

client.addConverterFactory(GsonConverterFactory.create()) // json 解析器

client.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 支持RxJava

复制代码

如果想支持其他解析器也是可以的

在 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 {

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)

复制代码

ccce081d9f9e3b92a931cd6ed2b8321b.png

有时候可能不需要那么多的日志 可以使用 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 才是最后的王道,

b739ec46bb5c46d9c0aa4ce35ba1ea56.png

关于找一找教程网

本站文章仅代表作者观点,不代表本站立场,所有文章非营利性免费分享。

本站提供了软件编程、网站开发技术、服务器运维、人工智能等等IT技术文章,希望广大程序员努力学习,让我们用科技改变世界。

[RxJava+Retrofit 搭建网络请求框架]http://www.zyiz.net/tech/detail-138631.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值