Android different networks seamlessly switch request frame

A recent study Netease open class, there are many large cattle share, is to learn the basic code is the code of video heavy knock to the side, and in order to enhance the use of kotlin language, write code that will cut the latter to kotlin language.

The best language is used to describe the map, so I was through drawing and code to explain the principle.

Architecture Description:

1. This architecture is very simple, as there is a common interface to FIG IHttpProcess, there is only one request method post network, the interface HttpHelper, VolleyProcess, OkhttpProcess other classes to implement this method.

interface IHttpprocessor{
    fun post(url : String,params : HashMap<String,Object>,callback : ICallBack)
}

2.HttpHelper embodiment there is a single IHttpProcess a class object, such as a parent class can hold VolleyProcess, OkhttpProcess other different frame classes,

Here the frame is switched by setting different IHttpProcess class object, if you want to add additional network interface can only be achieved IHttpProcess frame.

class HttpHelper : IHttpprocessor{
    //具体网络框架实现类
    var mIHttpprocessor : IHttpprocessor? = null
    //单例
    companion object {
        private var instance : HttpHelper? = null
        get(){
            if(field == null){
                field = HttpHelper();
            }
            return field;
        }

        @Synchronized
        fun instance():HttpHelper{
            return instance!!
        }
    }
    
    //初始化设置网络框架
    fun init(httpPrecoss:IHttpprocessor){
        mIHttpprocessor = httpPrecoss
    }

    //调用网络请求方法
    override fun post(url: String, params: HashMap<String, Object>, callback: ICallBack) {
        //参数处理
        var finalUrl:String  = appendParams(url,params)
        //具体调用网络框架
        mIHttpprocessor?.post(finalUrl,params,callback)
    }

    private fun appendParams(url: String, params: HashMap<String, Object>):String {
        if(params == null || params.isEmpty()){
            return url
        }
        val stringBuild:StringBuilder = StringBuilder(url)
        if(stringBuild.indexOf("?") <= 0){
            stringBuild.append("?")
        }else{
            if(!stringBuild.toString().endsWith("?")){
                stringBuild.append("&")
            }
        }

        params.forEach {
            stringBuild.append("&"+it.key).append("=").append(encode(it.value.toString()))
        }
        Log.d("HttpHelper","url = " +stringBuild.toString())
        return stringBuild.toString()
    }

    private fun encode(str:String):String{
        return URLEncoder.encode(str,"utf-8")
    }

}

3. The framework uses a specific network, here I only spent two VolleyProcess and OkhttpProcess framework code is very simple to call it

OkhttpProcessle class

class OkHttpProcessor : IHttpprocessor{

    private var client : OkHttpClient? = null
    private var mHandler : Handler? = null
    constructor(){
        client = OkHttpClient()
        mHandler = Handler(Looper.getMainLooper())
    }

    override fun post(url: String, params: HashMap<String, Object>, callback: ICallBack) {
       val requstbody : RequestBody = appendBody(params)
       val request: Request? = Request.Builder().url(url).post(requstbody).build()
        client?.newCall(request)?.enqueue(object : Callback{
            override fun onFailure(call: Call, e: IOException) {
                callback?.onFail()
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                if(response.isSuccessful()){
                    val str : String = response.body()!!.string()
                    mHandler?.post(Runnable {
                        callback?.onSuncess(str)
                    })
                }
            }

        })
    }

    private fun appendBody(params: HashMap<String, Object>): RequestBody {
        val body : FormBody.Builder = FormBody.Builder()
        if(params == null || params.isEmpty()){
            return body.build();
        }
        params?.forEach(){
            body.add(it.key,it.value.toString())
        }
        return body.build()
    }

}

VolleyProcess class

class VolleyPorcess : IHttpprocessor {

    companion object {
        var mQueue:RequestQueue ? = null
    }

    constructor(context:Context){
        mQueue = Volley.newRequestQueue(context)
    }

    override fun post(url: String, params: HashMap<String, Object>, callback: ICallBack) {
        val stringRequest:StringRequest = StringRequest(Request.Method.POST,url,Response.Listener<String> {
            callback.onSuncess(it)
        },Response.ErrorListener{
            Log.d("VolleyPorcess",it.toString())
            callback.onFail()
        })
        mQueue?.add(stringRequest)
    }
}

4. Initialize the network provided the network frame is a frame that codes to switch

class MyApplication : Application(){

    override fun onCreate() {
        super.onCreate()
        //HttpHelper.instance().init(OkHttpProcessor())//使用okhttp
        HttpHelper.instance().init(VolleyPorcess(this))//使用volley
    }
}

5. The final step is to call

 val params: HashMap<String, Object> = HashMap()
        params.put("province_id", 1 as Object)
        HttpHelper.instance().post(
                url,
                params,
                object : HttpCallBack<Response>() {

                    override fun onSucess(response: Response) {
                        Log.d(TAG,response.toString())
                    }
                }
        )

to sum up:

Code structure is very simple and clear, but this idea is very important, in the project for a reasonable package code, Component Business extraction is very important.

Portal

 

 

 

Published 92 original articles · won praise 27 · views 90000 +

Guess you like

Origin blog.csdn.net/zhuxingchong/article/details/94382869