Kotlin 将自定义标头设置为websocket请求(ktor)
我正在从客户端建立websocket连接,如下所示:Kotlin 将自定义标头设置为websocket请求(ktor),kotlin,websocket,http-headers,ktor,Kotlin,Websocket,Http Headers,Ktor,我正在从客户端建立websocket连接,如下所示: val client = HttpClient(CIO).config { install(WebSockets) } client.webSocket( method = HttpMethod.Get, host = "127.0.0.1", port = 8080, path = "/api") { // Send and receive messages
val client = HttpClient(CIO).config {
install(WebSockets)
}
client.webSocket(
method = HttpMethod.Get,
host = "127.0.0.1",
port = 8080,
path = "/api") {
// Send and receive messages
}
我想做的是向这个请求添加http头
Ktor有一个相当长的文档,但尽管如此,我无法找到如何做到这一点。毕竟找到了答案:
client.webSocket(
method = HttpMethod.Get,
host = "127.0.0.1",
port = 8080,
path = "/api",
request = {
header("my_header", "my_header_value")
}
) {
// more
怎么找到这个?从webSocket
的签名中:
suspend fun HttpClient.webSocket(
method: HttpMethod = HttpMethod.Get,
host: String = "localhost",
port: Int = DEFAULT_PORT,
path: String = "/",
request: HttpRequestBuilder.() -> Unit = {},
block: suspend DefaultClientWebSocketSession.() -> Unit
): Unit
这里的HttpRequestBuilder
听起来像是可以定制请求的东西(确实有一些关于这方面的文档)
签名意味着请求
应该是一个作用域闭包,其中此
将是HttpRequestBuilder
然后,这个闭包可以设置标题或更改其他内容。例如,有