Retrofit是当前应用非常广泛的网络请求框架,通常结合RxJava来进行网络请求,本文将展示一个采用RxJava+Retrofit的网络请求demo,感兴趣的可以了解一下
简要介绍
Retrofit是当前应用非常广泛的网络请求框架,通常结合RxJava来进行网络请求,本文将展示一个采用RxJava+Retrofit的网络请求demo.
集成步骤
1、app工程的build.gradle中添加依赖
//retrofit2
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
//rxjava2
implementation 'io.reactivex.rxjava2:rxjava:2.2.2'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
//配合Rxjava2 使用
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
2、在AndroidManifest.xml中添加权限
<uses-permission android:name="android.permission.INTERNET"/>
3、添加数据类Task
data class Task(var id: Int, var name: String?)
4、 添加网络请求类NetworkService
import io.reactivex.Observable;
import retrofit2.http.GET;
public interface NetworkService {
@GET("data.json")
Observable<Task> query();
}
5、activity中调用
class MainActivity : AppCompatActivity() {
private val BASE_URL = "https://raw.githubusercontent.com/cxyzy1/rxjava_retrofit_demo/master/"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
queryData()
}
private fun queryData() {
//创建Retrofit对象
val retrofit = Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
//获取UserMsgService对象
val networkService = retrofit.create(NetworkService::class.java)
networkService.query()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<Task> {
override fun onSubscribe(d: Disposable) {
}
override fun onNext(task: Task) {
contentTv.text = task.toString()
}
override fun onError(e: Throwable) {
Log.v("", e.message)
}
override fun onComplete() {
}
})
}
}
网络请求结果截图
Demo源代码
https://github.com/cxyzy1/rxjava_retrofit_demo
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:RxJava+Retrofit实现网络请求封装的方法
基础教程推荐
猜你喜欢
- iOS开发 全机型适配解决方法 2023-01-14
- IOS获取系统相册中照片的示例代码 2023-01-03
- iOS开发使用XML解析网络数据 2022-11-12
- iOS Crash常规跟踪方法及Bugly集成运用详细介绍 2023-01-18
- Flutter进阶之实现动画效果(三) 2022-10-28
- iOS中如何判断当前网络环境是2G/3G/4G/5G/WiFi 2023-06-18
- Android实现短信验证码输入框 2023-04-29
- Android开发Compose集成高德地图实例 2023-06-15
- Android Compose自定义TextField实现自定义的输入框 2023-05-13
- MVVMLight项目Model View结构及全局视图模型注入器 2023-05-07