先贴工具类的代码
object HttpUtil {
//这是Get请求
fun sendOkHttpGetRequest(address:String, callback: okhttp3.Callback){
val client= OkHttpClient()
val request= Request.Builder().url(address).build()
//必须调用enqueue方法,异步网络请求
client.newCall(request).enqueue(callback)
}
//这是Post请求
fun sendOkHttpPostRequest(address: String, requestBody: RequestBody, callback:okhttp3.Callback){
val client=OkHttpClient()
val request=Request.Builder().url(address).post(requestBody).build()
//必须调用enqueue方法,异步网络请求
client.newCall(request).enqueue(callback)
}
}
需要使用工具类的时候就HttpUtil.fun()
HttpUtil.sendOkHttpGetRequest("https://wanandroid.com/user_article/list/$curPage/json",
object : Callback {
override fun onFailure(call: Call, e: IOException) {
}
override fun onResponse(call: Call, response: Response) {
//网络请求成功后,解析json数据
val responseData = response.body?.string()
//调用方法刷新recycleView数据,但注意在此函数内是子线程不能直接更新ui
recycleViewData(responseData)
}
})
val username = mEdUsername.text.toString()
val password = mEdPassword.text.toString()
//Post请求需要先bulid requestBody
val requestBody = FormBody.Builder()
.add("username", username)
.add("password", password)
.build()
HttpUtil.sendOkHttpPostRequest(
"https://www.wanandroid.com/user/login",
requestBody,
object : Callback {
override fun onFailure(call: Call, e: IOException) {
}
override fun onResponse(call: Call, response: Response) {
//网络请求成功后,解析json数据
val responseData = response.body?.string()
}
})