kotlin-OKHttp网络异步请求后根据响应内容执行进一步操作

封装OKhttp

package com.lettytrain.notesapp.util


import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.MediaType.Companion.toMediaType


object OKHttpUtils {
    //实现cookie持久化
    val client = OkHttpClient().newBuilder().cookieJar(PersistenceCookieJar()).build()

    fun get(url: String, callback: OKHttpCallback) {
        callback.url = url
        val request = Request.Builder().url(url).build()
        client.newCall(request).enqueue(callback)
    }

    val JSON = String.format("application/json; charset=utf-8").toMediaType()

    fun post(url: String, json: String, callback: OKHttpCallback) {
        callback.url = url
        val requestBody = RequestBody.create(JSON, json)
        val request = Request.Builder().url(url).build()
        client.newCall(request).enqueue(callback)
    }
}


package com.lettytrain.notesapp.util

import android.util.Log
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

open class OKHttpCallback : Callback {
    var url: String = ""
    var result: String = ""
    //成功
    override fun onResponse(call: Call, response: Response) {
        result = response.body?.string().toString()
        Log.d("OKHttpCallback", "url:${url}")
        onFinish("success", result)
    }

    //失败
    override fun onFailure(call: Call, e: IOException) {
        Log.d("OKHttpCallback", "url:${url}")
        Log.d("OKHttpCallback", "请求失败${e.toString()}")
        onFinish("failure", e.toString())
    }

    open fun onFinish(status: String, msg: String) {
        Log.d("OKHttpCallback", "url:${url},status:${status},message:${msg}")
    }


}

主线程中调用时

 private fun newUserRegister() {
        signup.setOnClickListener {
            //判空
            if (username.text.isNullOrEmpty()) {
                Toast.makeText(this, "UserName is Requeried", Toast.LENGTH_SHORT).show()
            }
            if (password.text.isNullOrEmpty()) {
                Toast.makeText(this, "Password is  Requeried", Toast.LENGTH_SHORT).show()
            }
            if (confirm.text.isNullOrEmpty()) {
                Toast.makeText(this, "Please input your password again.", Toast.LENGTH_SHORT).show()
            }
            //两次密码不一致
            if (!confirm.text.toString().equals(password.text.toString())) {
                Toast.makeText(this, "The two password are inconsistent", Toast.LENGTH_SHORT).show()
                password.setText("")
                confirm.setText("")
            } else {
                //发送网络请求,用onfinish拿到结果
                OKHttpUtils.get(
                    "http://10.236.11.105:8080/portal/user/signup.do?userName=${username.text.toString()}&password=${password.text.toString()}",
                    object : OKHttpCallback() {
                        override fun onFinish(status1: String, result: String) {
                            super.onFinish(status1, result)
                            //解析数据

                            var jsobj = Gson().fromJson(result, ServerResponse::class.java)
                            val status = jsobj.status
                            val msg = jsobj.msg
                            if (status == 6 && msg.equals("用户名存在")) {
                                //如果用户名已经存在
                                Looper.prepare()
                                Toast.makeText(
                                    MyApplication.context,
                                    "The username already exists. ",
                                    Toast.LENGTH_SHORT
                                ).show()
                                username.setText("")
                                password.setText("")
                                confirm.setText("")
                                Looper.loop()

                            } else if (status == 0 && msg.equals("注册成功")) {
                                Looper.prepare()
                                username.setText("")
                                password.setText("")
                                confirm.setText("")
                                Toast.makeText(
                                    MyApplication.context,
                                    "To Login......",
                                    Toast.LENGTH_SHORT
                                )
                                    .show()

                                val intent =
                                    Intent(MyApplication.context, LoginActivity::class.java)
                                startActivity(intent)
                                Looper.loop()
                                // supportFragmentManager.popBackStack()
                                //设置有个交互按钮,让用户选择是去登录还是继续留在这里
                            } else {
                                //链接失败
                                Looper.prepare()
                                Toast.makeText(
                                    MyApplication.context,
                                    "The connection fails,please try again. ",
                                    Toast.LENGTH_SHORT
                                ).show()
                                username.setText("")
                                password.setText("")
                                confirm.setText("")
                                Looper.loop()
                            }
                        }
                    }
                )
            }
        }

你可能感兴趣的:(kotlin,kotlin,网络,android)