引入依赖
implementation 'com.squareup.retrofit2:retrofit:2.6.1' implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
添加权限
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 }
接口封装
object ServiceCreator { private const val base_URL = "http://10.0.2.2/" private val retrofit = Retrofit.Builder() .baseUrl(base_URL) .addConverterFactory(GsonConverterFactory.create()) .build() funcreate(serviceClass: Class ): T = retrofit.create(serviceClass) }
简单使用
val appService = ServiceCreator.create(AppService::class.java) appService.getAppData().enqueue(object : Callback { override fun onResponse(p0: Call, p1: Response) { val app = p1.body() Log.e(TAG, "onResponse: $app") } override fun onFailure(p0: Call, p1: Throwable) { p1.printStackTrace() } })
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)