简要介绍
Retrofit是当前应用非常广泛的网络请求框架,而Coroutines则是Kotlin中用于执行异步任务的框架,比RxJava还要方便易用,本文将展示一个采用Coroutines+Retrofit的网络请求demo. 若想了解RxJava+Retrofit,可参考《RxJava+Retrofit实现网络请求》
集成步骤- app工程的build.gradle中添加依赖
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"
implementation "com.squareup.retrofit2:retrofit:2.6.0"
implementation "com.squareup.retrofit2:converter-gson:2.6.0"
implementation "com.squareup.okhttp3:logging-interceptor:3.11.0"
implementation "com.squareup.okhttp3:okhttp:3.14.2"
- 在AndroidManifest.xml中添加权限
- 添加数据类Task
data class Task(var id: Int, var name: String?)
- 添加网络请求类NetworkService
interface NetworkService {
@GET("cxyzy1/coroutineRetrofitDemo/raw/master/data.json")
suspend fun query(): Task
}
- activity中调用
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
queryData()
}
private fun queryData() {
val okHttpClient = OkHttpClient.Builder()
.apply {
addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY })
}.build()
val retrofit = Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://gitee.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val networkService = retrofit.create(NetworkService::class.java)
GlobalScope.launch(Dispatchers.Main) {
val result = withContext(Dispatchers.IO) { networkService.query() }
contentTv.text = result.toString()
}
}
}
网络请求结果截图
https://gitee.com/cxyzy1/coroutineRetrofitDemo/tree/master/app
安卓开发技术分享: https://blog.csdn.net/yinxing2008/article/details/84555061 点击关注专栏,查看最新技术分享 更多技术总结好文,请关注:「程序园中猿」