I'm establishing a websocket connection from the client like this:
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
}
What I would like to do is add http headers to this request.
Ktor has a pretty length documentation, but despite this I am not able to locate how to do this.
Found out the answer after all:
client.webSocket(
method = HttpMethod.Get,
host = "127.0.0.1",
port = 8080,
path = "/api",
request = {
header("my_header", "my_header_value")
}
) {
// more
How to find this? From the signature of 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
Here HttpRequestBuilder
sounds like something that can customize requests (and indeed there is some documentation on that).
The signature means request
should be a scoped closure where this
will be HttpRequestBuilder
.
This closure can then set headers or change other things. There is, for example, HttpRequestBuilder.header
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With