依旧是网络请求大头,以最快的方式写
协程 Retrofit #
class Auth(private val token: String) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
.newBuilder()
.addHeader("Authorization","Bearer $token")
.build()
return chain.proceed( request)
}
}
fun createRetrofitWithAuth() :Retrofit{
return Retrofit.Builder()
.baseUrl("http://124.93.196.45:10193/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
fun createRetrofitWithAuth(token:String) :Retrofit{
val client=OkHttpClient.Builder()
.addInterceptor(Auth(token))
.build()
return Retrofit.Builder()
.baseUrl("http://124.93.196.45:10193/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
}
定义接口
interface ApiService {
@GET("/prod-api/api/public-welfare/public-welfare-type/list")
suspend fun WelfareType(): WelfareType
@POST("/prod-api/api/login")
suspend fun Login(@Body body:LoginBody): Login
@GET("/prod-api/api/public-welfare/ad-banner/list")
suspend fun Banner(): Banner
}
viewmodel
class LoginViewModel: ViewModel() {
private val _data = MutableLiveData<Login>()
val data: LiveData<Login> = _data
val loginApiService = createRetrofitWithAuth().create(ApiService::class.java)
fun login(body:LoginBody){
viewModelScope.launch { _data.value=loginApiService.Login(body) }
}
}
ui 中使用
val login=findViewById<Button>(R.id.login)
val username=findViewById<EditText>(R.id.username)
val password=findViewById<EditText>(R.id.password)
val viewmodel=LoginViewModel()
login.setOnClickListener {
if(username.text.toString() !=""&& password.text.toString()!=""){
viewmodel.login(LoginBody(username=username.text.toString(), password = password.text.toString()))
viewmodel.data.observe(this){
Log.d("Login",it.toString())
if(it.code==200){
this.applicationContext.getSharedPreferences("app",Context.MODE_PRIVATE).edit {
putString("token",it.token)
}
startActivity(Intent(this,MainActivity::class.java))
Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show()
}
}
}
}