【问题标题】:Set custom headers to websocket request (ktor)将自定义标头设置为 websocket 请求 (ktor)
【发布时间】:2019-08-21 19:36:56
【问题描述】:

我正在从客户端建立一个 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 有一个相当长的文档,但尽管如此,我还是无法找到如何做到这一点。

【问题讨论】:

    标签: kotlin websocket http-headers ktor


    【解决方案1】:

    终于找到答案了:

    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

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 1970-01-01
      • 2017-05-27
      • 2015-01-15
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 2016-08-15
      • 2016-05-16
      相关资源
      最近更新 更多