Android使用Kotlin協程封裝網絡庫

概述

         最近又要替換網絡庫成了,致使全部的業務代碼都要替換且要從新測試迴歸。爲了防止後續再遇到這樣事情,下降替換核心庫的成本,現利用協程對網絡庫進行封裝。android

 

理想API調用方式

launch {
            val response = TestReq(q = "電腦").request<TestResponse>()
            Toast.makeText(this, response?.result?.toString()?:"網絡異常", Toast.LENGTH_SHORT).show()
            }

請求定義

@URL("https://suggest.taobao.com/sug")
@GET
data class TestReq(var code: String = "utf-8", val q: String) : IReq


class TestResponse {
    var result: List<Any>? = null
}

說明

    launch是對Context的類擴展,對於Activity而言能夠在銷燬的時候關閉協程;其餘場景能夠本身管理協程。例如:git

import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() , CoroutineScope by MainScope() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        launch {
            val response = TestReq(q = "電腦").request<TestResponse>()
            Toast.makeText(this@MainActivity, response?.result?.toString()?:"網絡異常", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
    }

}

 

使用

引用

implementation 'com.zhangzheng.easyhttp:library:1.0.1'

初始化

默認(HttpUrlConnection)github

EasyHttp.init(DefaultAdapter(GsonJsonParse()))
implementation 'com.google.code.gson:gson:2.8.6'

OkHttpjson

EasyHttp.init(OKHttpAdapter(GsonJsonParse()))
implementation 'com.squareup.okhttp3:okhttp:3.8.0'
    implementation 'com.squareup.okio:okio:1.12.0'

 implementation 'com.google.code.gson:gson:2.8.6'

Vollery網絡

EasyHttp.init(VolleyAdapter(this,GsonJsonParse()))
implementation 'com.android.volley:volley:1.1.1'

 implementation 'com.google.code.gson:gson:2.8.6'

若是使用的是FastJson能夠替換解析器ide

GsonJsonParse() --> FastJsonParse()
implementation 'com.alibaba:fastjson:1.2.37'

若是協程不可用,檢查協程庫是否引入了測試

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"

 

自定義擴展

        本身擴展能夠實現EasyHttp.IAdapter,對於後續替換網絡請求核心庫只須要開發適配器就能夠了。對於json解析能夠實現IResponseParse來擴展。示例以下:ui

 

IAdapterthis

class OKHttpAdapter(var parse: IResponseParse) : EasyHttp.IAdapter {
    override suspend fun request(url: String, params: Map<String, String>, isGet: Boolean): String {
        val okHttpClient = OkHttpClient()
        val formBody = FormBody.Builder()
        params.forEach {
            formBody.add(it.key,it.value)
        }

        val request: Request =if(isGet){
             Request.Builder().url(url.urlWithParam(params)).method("GET", null)
        }else{
             Request.Builder().url(url).method("POST", createParamBody(params))
        }.build()

        val call: Call = okHttpClient.newCall(request)
        return call.execute().body()?.string()?:""
    }

    override fun <T> parse(value: String, clazz: Class<T>)=parse.parse(value,clazz)


    private fun createParamBody(params: Map<String, String>):FormBody{
        val formBody = FormBody.Builder()
        params.forEach {
            formBody.add(it.key,it.value)
        }
        return formBody.build()
    }
}

 

IResponseParsegoogle

class FastJsonParse :IResponseParse{

    override fun <T > parse(value: String, clazz: Class<T>)=JSON.parseObject(value,clazz)

}

 

github地址:https://github.com/long8313002/EasyHttp

相關文章
相關標籤/搜索