使用建造者模式实例化Retrofit
private fun retrofit(): Retrofit = Retrofit.Builder()
// 后端接口地址
.baseUrl("http://192.168.0.100:00002")
// 将值转化为JSON格式
.addConverterFactory(GsonConverterFactory.create())
.build()
// 实例化接口
val webservice:Webservice = retrofit().create(Webservice::class.java)
定义请求接口:
interface Webservice { /** * 请求列表 * @param peddle * @return liveList */ @POST("/live/find/all") fun getLiveList(@Body peddle: Peddle): Call<LiveList> }
在类中使用
/* * Copyright (c) 2020 www.ai-wsd.com Inc. All rights reserved */ class UserRepository { private val webservice: Webservice = ApiService.webservice fun getLiveList():LiveData<LiveList>{ val data = MutableLiveData<LiveList>() // peddle为实体类 val peddle = Peddle(1,3) webservice.getLiveList(peddle).enqueue(object : Callback<LiveList> { override fun onResponse(call: Call<LiveList>, response: Response<LiveList>) { data.value = response.body() } override fun onFailure(call: Call<LiveList>, t: Throwable) { Log.e(TAG, "onFailure: $t") } }) return data } companion object{ const val TAG = "UserRepository" } }
依赖添加
implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0'