美文网首页
DSL網絡請求

DSL網絡請求

作者: 蓝Renly | 来源:发表于2018-08-15 19:44 被阅读0次

知識點:1.構建器的使用;2.接口(或者函數)回調;

DSL网络请求构建器:

package pers.lansir.Demo

import java.net.HttpURLConnection
import java.net.URL
import java.util.*

fun main(args: Array<String>) {
    http {
        path = "www.baidu.com"
        method = "GET"
        onSuccess { str:String ->
            println("调用成功")
        }
        onError { str:String ->
            println("调用失败")
        }
    }
}
fun MyRequest.onSuccess(block: (String) -> Unit) {
    this.onSuccess = block//注意:此处容易想不到!
}
fun MyRequest.onError(block: (String) -> Unit) {
    this.onError = block
}
fun http(block: MyRequest.() -> Unit) {
    //此处如果创建val httpUtil = HttpUtil(),里面的参数没办法传递,因此需要构建器,来传递参数
    val myRequest = MyRequest()
    myRequest.block()
    myRequest.send()
}
//创建构建器
class MyRequest(var path: String? = null, var method: String? = null, var onSuccess: ((String) -> Unit)? = null, var onError: ((String) -> Unit)? = null) {
    //构建器里的send方法
    fun send() {
        val httpUtil = HttpUtil()
        httpUtil.sendRequest(path, method, onSuccess, onError)
    }
}
//HttpUtil类
class HttpUtil {
    //请求方法及其参数(请求路径(网址),请求方法(get/post),请求成功,请求失败)
    fun sendRequest(path: String?, method: String?, onSuccess: ((String) -> Unit)?, onError: ((String) -> Unit)?) {
        //因为网络请求需要耗时较多,所以需要另开线程操作
        Thread {
            //常见URL对象
//            val url = URL(path)
            println("创建URL对象")
            //打开网络连接
//            val conn = url.openConnection() as HttpURLConnection
            println("打开网络连接")
            //获取响应码
//            val resCode = conn.responseCode
            println("获取响应码")
            val resCode = Random().nextInt(10)
            if (resCode % 2 == 0) {
                onSuccess?.invoke("调用成功")
            } else {
                onError?.invoke("调用失败")
            }
        }.start()
    }
}

相关文章

网友评论

      本文标题:DSL網絡請求

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