【Android】【Kotlin】使用【Retrofit】基本使用

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
}
//ResponseBody可替换成自己写的Bean类

ViewModel使用

//ResponseBody可替换成自己写的Bean类
    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")
}

//livedata的监听
viewmodel.loginInfo.observe(this,{
   Log.e("TAG", "获取的数据:${it}")
 })

你可能感兴趣的:(Android学习笔记,android,android,studio)