kotlinrequesthttp-headersktorktor-client

Setting headers with the headers block is not working with Ktor HTTP Client


I am using Ktor Client 3.1.3 in my Kotlin application. The HTTP Client is initialised like this:

val httpClient = HttpClient {
    install(HttpCookies)
    install(ContentNegotiation) {
        json()
    }
    install(Logging) {
        logger = Logger.DEFAULT
        level = LogLevel.ALL
    }
}

I am trying to send a post request and set some of its headers. It works when I do this:

val resp = httpClient.post(myUrl) {
    header(myHeaderKey, myHeaderValue)

    setBody(myBody)
}

But it doesn't when I do this:

val resp = httpClient.post(myUrl) {
    headers {
        set(myHeaderKey, myHeaderValue)
    }

    setBody(myBody)
}

I the first case, the header appears in the application log, and in the second, it doesn't. I would like to use the second version since I have a lot of headers to set and it is cleaner. Why is it not working?


Solution

  • I found the problem. I was using the wrong import. I had:

    import io.ktor.http.headers
    

    But it should be:

    import io.ktor.client.request.headers