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

时间:2019-03-31 13:43:02

标签: 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
}

我想做的就是向此请求添加http标头。

Ktor有相当长的文档,但是尽管如此,我仍然找不到执行该操作的方法。

1 个答案:

答案 0 :(得分:0)

毕竟找到了答案:

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

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