将自定义 headers 设置为 websocket 请求(哪个)

Set custom headers to websocket request (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
}

我想做的是将 http headers 添加到此请求中。

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 听起来像是可以自定义请求的东西(确实有一些相关文档)。

签名意味着 request 应该是一个作用域闭包,其中 this 将是 HttpRequestBuilder

此闭包然后可以设置 headers 或更改其他内容。例如,HttpRequestBuilder.header.