美文网首页
Kotlin的特性简单封装OkHttp

Kotlin的特性简单封装OkHttp

作者: 有没有口罩给我一个 | 来源:发表于2019-04-27 16:25 被阅读0次

之前也有过几篇Kotlin的文章,最近由于项目比较忙就没有怎么更新,今天就热热身讲Kotlin特性简单分装OkHttp。

class RequestBuilder : Callback {

    var urls: String = ""

    var method: String = "GET"

    var body: RequestBody? = null

    var timeout: Long = 3000

    var success: ((Response) -> Unit)? = null

    var faild: ((Throwable) -> Unit)? = null

    fun onSuccess(onSuccess: (Response) -> Unit) {
        success = onSuccess
   }

    fun onFail(onError: (Throwable) -> Unit) {
        faild = onError
    }

     override fun onFailure(call: Call, e: IOException) {
         faild?.invoke(e)
     }

      override fun onResponse(call: Call, response: Response) {
          success?.invoke(response)
      }

    fun request() = OkHttpClient.Builder().run {
         connectTimeout(timeout, TimeUnit.MILLISECONDS)
        readTimeout(timeout, TimeUnit.MILLISECONDS)
        retryOnConnectionFailure(true)
        build().newCall(
            when (method) {
                "post", "Post", "POST" -> Request.Builder().url(urls).post(body!!).build()
                else -> Request.Builder().url(urls).build()
            }
    )
  }.enqueue(this)
}

fun http(init: RequestBuilder.() -> Unit) {
    val wrap = RequestBuilder()
    wrap.init()
    wrap.request()
}

怎么使用?

 http {
        urls = ""
        method = "GET"
        timeout = 2500
        onSuccess {

        }
        onFail {

        }
    }

是不是很简洁,所以这篇文章就到这。

相关文章

网友评论

      本文标题:Kotlin的特性简单封装OkHttp

      本文链接:https://www.haomeiwen.com/subject/wbuknqtx.html