基于OKHttp3简单封装的网络请求类

使用

implementation "com.squareup.okhttp3:okhttp:latest_version"

构造

链式调用生成OKHttpClient对象。

设置拦截器

基础的日志输出拦截器 loggingInterceptor,此时还得引入如下包:

implementation 'com.squareup.okhttp3:logging-interceptor:latest_version'

头拦截器 headInterceptor ,主要用于接口调用都得加入一些固定的认证参数之类的,这里便可以很方便的在每次发起请求后进行添加。

调用

OkHttpUtils.getInstance(),采用单例模式进行全局管理和调用。

支持同步或者异步的Get和Post请求。

上代码

package com.dingo.net

import com.dingo.log.LogManager
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException
import java.util.concurrent.TimeUnit

class OkHttpUtils private constructor() {

    private var httpClient: OkHttpClient? = null
    private val timeUnit: TimeUnit = TimeUnit.SECONDS
    private val connectTimeOut: Long = 10
    private val readTimeOut: Long = 10
    private val writeTimeOut: Long = 10

    private val logger = LogManager.getInstance().getLog(OkHttpUtils::class.java.simpleName)

    private val headers = HashMap<String, String>()

    fun initHttpClient(): OkHttpClient? {
        val builder = OkHttpClient.Builder()
                .connectTimeout(connectTimeOut, timeUnit)
                .readTimeout(readTimeOut, timeUnit)
                .writeTimeout(writeTimeOut, timeUnit)

        //日志拦截器
        val loggingInterceptor = HttpLoggingInterceptor(
                HttpLoggingInterceptor.Logger { message -> logger.i(message) })
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        //添加头的拦截器
        val headInterceptor = Interceptor { chain ->
            val requestBuilder = chain.request().newBuilder()

            for ((key, value) in headers) {
                requestBuilder.addHeader(key, value)
            }

            chain.proceed(requestBuilder.build())
        }

        builder.addInterceptor(loggingInterceptor)
        builder.addInterceptor(headInterceptor)
        httpClient = builder.build()
        return httpClient
    }

    companion object {
        fun getInstance() = Holder.INSTANCE
    }

    private object Holder {
        val INSTANCE = OkHttpUtils()

        init {
            INSTANCE.initHttpClient()
        }
    }

    fun addHeader(key: String, value: String) = headers.put(key, value)

    fun removeHeader(key: String) = headers.remove(key)

    fun doSyncGet(url: String,
                  params: HashMap<String, String>? = null,
                  callBack: NetExecuteCallBack) {
        if (isStringEmpty(url)) {
            callBack.error(IllegalArgumentException("url is illegal"))
            return
        }

        val stringBuilder = StringBuilder()
        if (params != null && params.size > 0) {

            for ((k, v) in params) {
                stringBuilder.append(k).append("=").append(v).append("&")
            }

            stringBuilder.deleteCharAt(stringBuilder.length - 1)
        }

        val newUrl = if (stringBuilder.isBlank()) url else String.format("%s?%s", url, stringBuilder.toString())

        val mRequest = Request.Builder().url(newUrl).get().build()
        httpClient?.let {
            it.newCall(mRequest).enqueue(object : Callback {
                override fun onFailure(call: Call?, e: IOException?) {
                    callBack.error(e)
                }

                override fun onResponse(call: Call?, response: Response?) {
                    val result = response?.body().toString()
                    logger.i(result)
                    callBack.succeed(result)
                }
            })

//            it.newCall(mRequest).execute()
        }
    }

    fun doSyncPost(url: String,
                   params: HashMap<String, String>? = null,
                   callBack: NetExecuteCallBack) {
        if (isStringEmpty(url)) {
            callBack.error(IllegalArgumentException("url is illegal"))
            return
        }

        val requestBuilder = Request.Builder().url(url)

        if (params != null && params.size > 0) {
            val formBodyBuilder = FormBody.Builder()
            for ((k, v) in params) {
                formBodyBuilder.add(k, v)
            }
            requestBuilder.post(formBodyBuilder.build())
        }

        httpClient?.let {
            it.newCall(requestBuilder.build()).enqueue(object : Callback {
                override fun onFailure(call: Call?, e: IOException?) {
                    callBack.error(e)
                }

                override fun onResponse(call: Call?, response: Response?) {
                    callBack.succeed(response?.body().toString())
                }

            })
        }
    }

    fun doGet(url: String,
              params: HashMap<String, String>? = null,
              callBack: NetExecuteCallBack) {
        if (isStringEmpty(url)) {
            callBack.error(IllegalArgumentException("url is illegal"))
            return
        }

        val stringBuilder = StringBuilder()
        if (params != null && params.size > 0) {

            for ((k, v) in params) {
                stringBuilder.append(k).append("=").append(v).append("&")
            }

            stringBuilder.deleteCharAt(stringBuilder.length - 1)
        }

        val newUrl = if (stringBuilder.isBlank()) url else String.format("%s?%s", url, stringBuilder.toString())

        val mRequest = Request.Builder().url(newUrl).get().build()
        httpClient?.let {
            try {
                val response = it.newCall(mRequest).execute()
                callBack.succeed(response.body().toString())
            } catch (e: Exception) {
                callBack.error(e)
            }
        }
    }

    fun doPost(url: String,
               params: HashMap<String, String>? = null,
               callBack: NetExecuteCallBack) {
        if (isStringEmpty(url)) {
            callBack.error(IllegalArgumentException("url is illegal"))
            return
        }

        val requestBuilder = Request.Builder().url(url)

        if (params != null && params.size > 0) {
            val formBodyBuilder = FormBody.Builder()
            for ((k, v) in params) {
                formBodyBuilder.add(k, v)
            }
            requestBuilder.post(formBodyBuilder.build())
        }

        httpClient?.let {
            try {
                val response = it.newCall(requestBuilder.build()).execute()
                callBack.succeed(response.body().toString())
            } catch (e: Exception) {
                callBack.error(e)
            }
        }
    }

    fun isStringEmpty(str: String?): Boolean = str == null || str.isEmpty() || str.isBlank()
}

interface NetExecuteCallBack{

    fun succeed(result: String)

    fun error(e: Throwable?)
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值