api
"https://www.wanandroid.com/user/login"
Retrofit封装
object RetrofitClient {
private var retrofit: Retrofit? = null
const val BASE_URL="https://www.wanandroid.com/user/"
private fun getOkHttpClient(): OkHttpClient {
val builder = OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
return builder.build()
}
private fun getRetrofit(): Retrofit {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(getOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit!!
}
val service: ApiLoginService by lazy {
getRetrofit().create(ApiLoginService::class.java)
}
}
ApiLoginService
interface ApiLoginService {
@FormUrlEncoded
@POST("login")
suspend fun getLoginInfo(
@Field("username") username: String,
@Field("password") password: String
): ResponseBody
}
ViewModel使用
val loginInfo = MutableLiveData<ResponseBody>()
suspend fun getLoginInfo(strName: String, strPwd: String) {
var info = RetrofitClient.service.getLoginInfo(strName, strPwd)
loginInfo.postValue(info)
}
Activity使用
tv_login.setOnClickListener {
viewmodel.getLoginInfo("blue123", "123456")
}
viewmodel.loginInfo.observe(this,{
Log.e("TAG", "获取的数据:${it}")
})
|