https://kotlinlang.org logo
#ktor
Title
# ktor
m

Marcello Galhardo

11/10/2021, 2:26 PM
Hi there, I’m not sure if that is the right channel to ask that: I’m using Ktor Http Client and I need to add a dynamic header in all calls based on some conditions. With Retrofit I would normally add a simple interceptor and that would be the trick - but looking the docs I did not find a way to add interceptors when doing requests with Ktor (I’m finding very confusing Ktor docs, probably because I’m trying to find things for the client and I end up reading about the server and vice-verse). Can someone point me to examples on how to do that?
a

Aleksei Tirman [JB]

11/10/2021, 2:47 PM
Here is an example of how you can intercept a sending pipeline and add a header for each request:
Copy code
val client = HttpClient(Apache) {}

client.sendPipeline.intercept(HttpSendPipeline.State) {
    context.headers {
        append("my-header", "value")
    }
}

val r = client.get<String>("<https://httpbin.org/get>")
println(r)
m

Marcello Galhardo

11/10/2021, 2:53 PM
Oh, thank you very much. I will give it a try. 🙂