with(conn) {
requestMethod = method
doOutput = body != null
headers?.forEach(this::setRequestProperty)
}
这段代码是Kotlin标准库中 with 函数的应用,用于简化对 conn 对象的操作。以下是逐行解释:
-
with(conn) { ... }: 使用with作用域函数,使conn对象在大括号内成为隐式接收者,可以直接访问其属性和方法而无需前缀 -
requestMethod = method: 设置HTTP请求的方法类型(如GET、POST等),对应于conn.requestMethod -
doOutput = body != null: 配置连接是否应该向服务器发送数据。当 [body]不为空时设为true,表示需要输出流来发送请求体 -
headers?.forEach(this::setRequestProperty): 如果 [headers] 非空,则遍历每个键值对,并调用conn.setRequestProperty()方法将它们设置为HTTP头信息
这种写法让代码更简洁易读,避免了重复书写 conn. 前缀。