Retrofit的简单使用

引入依赖

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()
    }
})

你可能感兴趣的:(安卓,http,网络协议,网络)