我正在像这样从客户端建立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有相当长的文档,但是尽管如此,我仍然找不到执行该操作的方法。
答案 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
。