最近又开始堕落了,好久没写blog,这样不好不好,年初定的一周一篇技术文章还是要坚持下去,今天更新的是基于OkHttpUtils封装的通用CommonCallback。
OkHttpUtils是hongyang对OkHttp的封装类,OkHttpUtils的使用和配置,可以参考https://github.com/hongyangAndroid/okhttputils;这里我只是根据目前项目的需求,自定义了一个通用的CommonCallback:
CommonCallback
package com.vslimit.utils.net
import android.util.Log
import android.widget.Toast
import com.vslimit.App
import com.google.gson.Gson
import com.zhy.http.okhttp.callback.Callback
import okhttp3.Call
import okhttp3.Request
import okhttp3.Response
/**
* Created by vslimit on 17/3/10.
*/
abstract class CommonCallback<T>(val clazz: Class<T>) : Callback<T>() {
companion object{
val TAG = "CommonCallback"
}
override fun validateReponse(response: Response?, id: Int): Boolean {
Log.d(TAG, response!!.code().toString())
return super.validateReponse(response, id)
}
override fun onBefore(request: Request?, id: Int) {
super.onBefore(request, id)
}
override fun onAfter(id: Int) {
super.onAfter(id)
}
override fun onError(call: Call?, e: Exception?, id: Int) {
if (e is Exception) {
Toast.makeText(App.instance,"连接超时",Toast.LENGTH_LONG).show()
}
}
override fun parseNetworkResponse(response: Response?, id: Int): T {
val data = response!!.body().string()
return Gson().fromJson(data, clazz)
}
}
其中,validateReponse里面可以对一些自定义的http status进行校验,如token失效等;onError则是对一些异常进行友好提示。
在Activity使用如下:
fun login(v: View) {
val loginUrl = UrlConstant.URL_14412 + "/login"
if (!loginValidate(loginEt.text.toString(), passwordEt.text.toString())) {
alert(this@LoginActivity, "网络错误", "网络未连接,请检查网络")
return
}
mHandler.sendEmptyMessage(SHOW)
OkHttpUtils
.post()
.url(loginUrl)
.addParams("loginName", loginEt.text.toString())
.addParams("password", passwordEt.text.toString())
.build()
.execute(object : CommonCallback<UserRet>(UserRet::class.java) {
override fun onError(call: Call?, e: Exception?, id: Int) {
super.onError(call, e, id)
Log.d(TAG, e?.printStackTrace().toString())
mHandler.sendEmptyMessage(HIDE)
}
override
fun onResponse(response: UserRet, id: Int) {
mHandler.sendEmptyMessage(HIDE)
if (response.code == Result.SUCCESS) {
val ret = response.data
val token = ret?.token
Preference.with(this@LoginActivity).token = token
async() {
this@LoginActivity.startActivity<HomeActivity>()
}
this@LoginActivity.finish()
} else {
toast("${response.tip}")
}
}
})
}
至此,就完成了通用CommonCallback的封装。