将自定义标头设置为 websocket 请求 (ktor)

Mar*_*ark 4 websocket http-headers kotlin 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
}
Run Code Online (Sandbox Code Playgroud)

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

Ktor 有一个相当长的文档,但尽管如此,我无法找到如何做到这一点。

Mar*_*ark 10

终于找到答案了:

client.webSocket(
        method = HttpMethod.Get,
        host = "127.0.0.1",
        port = 8080,
        path = "/api",
        request = {
            header("my_header", "my_header_value")
        }
) {
    // more
Run Code Online (Sandbox Code Playgroud)

怎么找到这个?来自 的签名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
Run Code Online (Sandbox Code Playgroud)

HttpRequestBuilder听起来像是可以自定义请求的东西(实际上有一些相关的文档)。

签名手段request应该是一个作用域闭包,其中thiswill be HttpRequestBuilder

然后这个闭包可以设置标题或更改其他内容。例如,有HttpRequestBuilder.header.