开胃菜
话不多说,30s倒计时开始,先来看看如何发送一个Get请求,如下:
RxHttp.get("http://...") //第一步,确定请求类型,可以选择postForm、postJson等方法
.asString() //第二步,确定返回类型,这里返回String类型
.subscribe(s -> { //第三步,订阅观察者,第二步返回Observable对象
//请求成功
}, throwable -> {
//请求失败
});
Ok,倒计时结束!!! 到这,你已经学会了RxHttp的精髓。
是的,不用怀疑,就是这么简单,使用RxHttp,任意请求,任意返回数据类型,都遵循这三个步骤,我们称之为请求三部曲,如下:
重要事情说3遍
任意请求,任意返回数据类型,皆遵循请求三部曲
任意请求,任意返回数据类型,皆遵循请求三部曲
任意请求,任意返回数据类型,皆遵循请求三部曲
gradle依赖
-
OkHttp 3.14.x以上版本, 最低要求为API 21,如你想要兼容21以下,请依赖OkHttp 3.12.x,该版本最低要求 API 9
-
asXxx方法内部是通过RxJava实现的,而RxHttp 2.2.0版本起,内部已剔除RxJava,如需使用,请自行依赖RxJava并告知RxHttp依赖的Rxjava版本
1、必选
将jitpack
添加到项目的build.gradle
文件中,如下:
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
注:RxHttp 2.6.0版本起,已全面从JCenter迁移至jitpack
//使用kapt依赖rxhttp-compiler时必须
apply plugin: 'kotlin-kapt'
android {
//必须,java 8或更高
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'com.github.liujingxing.rxhttp:rxhttp:2.6.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.0' //rxhttp v2.2.2版本起,需要手动依赖okhttp
kapt 'com.github.liujingxing.rxhttp:rxhttp-compiler:2.6.0' //生成RxHttp类,纯Java项目,请使用annotationProcessor代替kapt
}
2、可选
android {
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
arguments = [
rxhttp_package: 'rxhttp', //非必须,指定RxHttp类包名
//传入你依赖的rxjava版本,可传入rxjava2、rxjava3,依赖RxJava时必须
rxhttp_rxjava: 'rxjava3'
]
}
}
}
}
dependen