Android okhttp网络请求封装 结合协程简单使用Kotlin版(2)

直接上代码:
OkhttpUtils:
class OkhttpUtils {

companion object{
    private var instance:OkhttpUtils? = null
    private var okhttp:OkHttpClient? = null

    @Synchronized
    fun getInstance():OkhttpUtils{
        if (instance == null) instance = OkhttpUtils()
        okhttp = OkHttpClient().newBuilder()
            .retryOnConnectionFailure(true)
            .connectTimeout(10000, TimeUnit.SECONDS) //连接超时
            .readTimeout(10000, TimeUnit.SECONDS) //读取超时
            .writeTimeout(10000, TimeUnit.SECONDS) //写超时
            .build()
        return instance!!
    }

}

/**
 * Get请求
 * @map 请求参数 map的key必须不同
 * @url 请求地址
 * @httpCallBack 回调
 */
fun  getRequest(map:HashMap,url:String,httpCallBak:HttpCallBack){
    if (TextUtils.isEmpty(url)){ return }
    var urlRequest:String = ""
    var urlL:String = ""
    if (map.size > 0){
        val list = ArrayList(map.keys)
        urlL = "$url?"
        for (key in map.keys){
            urlRequest += if (list[map.size - 1].equals(key)){
                key + "=" + map[key]
            }else{
                key + "=" + map[key] + "&"
            }
        }
        urlL += urlRequest
    }


    val request: Request = Request.Builder().url(urlL).build()
    val call: Call? = okhttp?.newCall(request)
    call?.enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            val error:String = e.printStackTrace().toString();
            //一定要Dispatchers.Main 不然协程不会切换线程
            GlobalScope.launch(Dispatchers.Main) {
                httpCallBak.onError(error)
            }

        }

        override fun onResponse(call: Call, response: Response) {
            val body: String? = response.body?.string();
            response.body?.let {
                //一定要Dispatchers.Main 不然协程不会切换线程
                GlobalScope.launch(Dispatchers.Main) {
                    body?.let { it1 ->
                        httpCallBak.onSuccess(it1)
                    }
                }

            }
        }

    })

}

/**
 * Post请求
 * @map 请求参数
 * @url 请求地址
 * @httpCallBack 回调
 */
fun  postRequest(map:HashMap,url:String,httpCallBak:HttpCallBack){
    if (TextUtils.isEmpty(url)){ return }
        var builder: FormBody.Builder = FormBody.Builder();
        if (map.size > 0){
            for (key in map.keys){
                key.let {
                    builder.add(it, map[it].toString())
                }
            }
        }

        val formBody:FormBody = builder.build()

        val request: Request = Request.Builder().url(url)
            .post(formBody)
            .build()
        val call: Call? = okhttp?.newCall(request)
        call?.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                val error:String = e.printStackTrace().toString();
                //一定要Dispatchers.Main 不然协程不会切换线程
                GlobalScope.launch(Dispatchers.Main) {
                    httpCallBak.onError(error)
                }

            }

            override fun onResponse(call: Call, response: Response) {
                val body: String? = response.body?.string();
                response.body?.let {
                    //一定要Dispatchers.Main 不然协程不会切换线程
                    GlobalScope.launch(Dispatchers.Main) {
                        body?.let { it1 ->
                                httpCallBak.onSuccess(it1)
                        }
                    }

                }

            }

        })



}

}
gradle引入:
//引入json解析框架
implementation ‘com.alibaba:fastjson:1.1.72.android’

//协程
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'

JsonUtils:
class JsonUtils {
companion object {
/**
* 解析json写法
*/
fun getJson(json: String?, clazz: Class?): RequestBodyContent? {
return JSONObject.parseObject(json, object : TypeReference(clazz) {})
}

    /**
     *实际使用方法解析json
     */
    fun  getJsonContent(json: String?,clazz: Class?):RequestBodyContent?{
        if (!TextUtils.isEmpty(json)){
            return getJson(json,clazz)
        }
        return null
    }

}

}
使用方法:PeopleBean是实体类最里面一层 RequestBodyContent是最外面一层
with(OkhttpUtils) {
getInstance().postRequest(map, “https://www.baidu.com/”, object : HttpCallBack {
override fun onError(errorLog: String) {
Toast.makeText(getApplication(),errorLog,Toast.LENGTH_SHORT).show()
}

                override fun onSuccess(message: String) {
                    var content: ? = JsonUtils.getJson(message,PeopleBean::class.java)
                    Toast.makeText(getApplication(),message,Toast.LENGTH_SHORT).show()
                }

            })


        }

你可能感兴趣的:(okhttp,网络请求,Android开发,android,kotlin,网络)