1、我们模拟一个网络请求的例子
import java.util.*
fun main(args: Array<String>) {
var httpUtil=HttpUtil()
httpUtil.sendRequest("http://www.baidu.com","get",{
println(it)
},{
println(it)
})
}
/**
* 模拟发送网络请求
*/
class HttpUtil {
interface CallBack {
fun onSuccess(result: String)
fun onError(e: String)
}
fun sendRequest(path: String?, method: String?, onsuccess: ((String) -> Unit)?, onError: ((String) -> Unit)?) {
println("pth=$path method=$method")
Thread {
//创建URL
// val url = URL(path)
println("创建URL")
//打开网络连接
// val conn = url.openConnection() as HttpURLConnection
println("打开网络连接")
//获取响应码
// val resCode = conn.responseCode
val code = Random().nextInt(100)
println("获取响应码")
if (code % 2 == 0) {
onsuccess?.invoke("结果正确了")
} else {
onError?.invoke("响应码不正确")
}
}.start()
}
}
输出:
或者
2、我们觉得这种请求网络的方式比较麻烦
var httpUtil=HttpUtil()
httpUtil.sendRequest("http://www.baidu.com","get",{
println(it)
},{
println(it)
})
想要这样做:更直观
http{
url="http://www.baidu.com"
method="get"
onSuccess{
println(it)
}
onFailed{
println(it)
}
}
修改代码:
import java.util.*
fun main(args: Array<String>) {
http{
url="http://www.baidu.com"
method="get"
onSuccess{
println(it)
}
onFailer{
println(it)
}
}
}
fun http(block:HttpUtilBuilder.()->Unit)
{
var httpUtilBuilder=HttpUtilBuilder()
block.invoke(httpUtilBuilder)
var httpUtil=HttpUtil()
httpUtil.sendRequest(httpUtilBuilder.url,httpUtilBuilder.method,httpUtilBuilder.onSuccess,httpUtilBuilder.onFailer)
}
fun HttpUtilBuilder.onSuccess(block: (result:String) -> Unit)
{
this.onSuccess=block
}
fun HttpUtilBuilder.onFailer(block: (result:String) -> Unit)
{
this.onFailer=block
}
class HttpUtilBuilder(var url: String?=null, var method: String?=null, var onSuccess: ((String) -> Unit)?=null, var onFailer: ((String) -> Unit)?=null)
/**
* 模拟发送网络请求
*/
class HttpUtil {
interface CallBack {
fun onSuccess(result: String)
fun onError(e: String)
}
fun sendRequest(path: String?, method: String?, onsuccess: ((String) -> Unit)?, onError: ((String) -> Unit)?) {
println("pth=$path method=$method")
Thread {
//创建URL
// val url = URL(path)
println("创建URL")
//打开网络连接
// val conn = url.openConnection() as HttpURLConnection
println("打开网络连接")
//获取响应码
// val resCode = conn.responseCode
val code = Random().nextInt(100)
println("获取响应码")
if (code % 2 == 0) {
onsuccess?.invoke("结果正确了")
} else {
onError?.invoke("响应码不正确")
}
}.start()
}
}
输出: