Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set custom headers to websocket request (ktor)

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.

like image 310
Mark Avatar asked Oct 21 '25 06:10

Mark


1 Answers

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.

like image 79
Mark Avatar answered Oct 23 '25 08:10

Mark