安卓

Coroutines+Retrofit实现网络请求

2021-09-17  本文已影响0人  蓝不蓝编程

简要介绍

Retrofit是当前应用非常广泛的网络请求框架,而Coroutines则是Kotlin中用于执行异步任务的框架,比RxJava还要方便易用,本文将展示一个采用Coroutines+Retrofit的网络请求demo. 若想了解RxJava+Retrofit,可参考《RxJava+Retrofit实现网络请求

集成步骤

  1. 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"
  1. 在AndroidManifest.xml中添加权限
<uses-permission android:name="android.permission.INTERNET"/>
  1. 添加数据类Task
    data class Task(var id: Int, var name: String?)
  2. 添加网络请求类NetworkService
interface NetworkService {
    @GET("cxyzy1/coroutineRetrofitDemo/raw/master/data.json")
    suspend fun query(): Task
}
  1. 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()
        }
    }
}

网络请求结果截图

Demo源代码

https://gitee.com/hspbc/coroutineRetrofitDemo/tree/master/app

关于我

厦门大学计算机专业 | 前华为工程师
分享编程技术,没啥深度,但看得懂,适合初学者。
Java | 安卓 | 前端 | 小程序 | 鸿蒙
公众号:花生皮编程

上一篇下一篇

猜你喜欢

热点阅读