之前也有过几篇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 {
}
}
是不是很简洁,所以这篇文章就到这。
网友评论