手机版 欢迎访问it开发者社区(www.mfbz.cn)网站

当前位置: > 开发

Retrofit的简单使用

时间:2021/12/2 16:36:07|来源:|点击: 次

引入依赖

implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.6.1'

添加权限

<uses-permission android:name="android.permission.INTERNET"/>

json数据

{"id":"1","name":"123qwe小王","version":"1"}

实体类

data class App(
    val id: String,
    val name: String,
    val version: String,
)

接口文件

interface AppService {
    @GET("get_data.json")
    fun getAppData(): Call<App>
}

接口封装

object ServiceCreator {
    private const val BASE_URL = "http://10.0.2.2/"

    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)
}

简单使用

val appService = ServiceCreator.create(AppService::class.java)
appService.getAppData().enqueue(object : Callback<App> {
    override fun onResponse(p0: Call<App>, p1: Response<App>) {
        val app = p1.body()
        Log.e(TAG, "onResponse: $app")
    }

    override fun onFailure(p0: Call<App>, p1: Throwable) {
        p1.printStackTrace()
    }
})

Copyright © 2002-2019 某某自媒体运营 版权所有