is there any Interceptor equivalent in Ktor like O...
# android
t
is there any Interceptor equivalent in Ktor like OkHttp?
t
When configuring Ktor
HttpClient
with the OkHttp engine, you have the opportunity to configure OkHttp to use interceptors.
t
what about other platform?
d
I haven't used OkHttp, but I assume interceptor is something like a ktor client feature that can intercept calls at various stages
t
By inspecting the
JsonFeature
, I noticed that it is possible to define interceptors with the following syntax :
Copy code
// Transformation on the request
httpClient.requestPipeline.intercept(HttpRequestPipeline.Transform) { playload ->
    // Do some things with the request, then send it to the next level
    val result = transformMyRequest(payload)
    proceedWith(result)
}

// Transformations on the response
httpClient.responsePipeline.intercept(HttpResponsePipeline.Transform) { (info, body) ->
    // Do some things with the response, then send it to the next level
    val result = transformMyResponse(info, body)
    proceedWith(result)
}
More details on Ktor Pipelining : https://ktor.io/advanced/pipeline.html#interceptors-and-the-pipelinecontext
t
You can also use this to install an `interceptor`:
Copy code
private fun HttpClientConfig<*>.authenticatedRequestsEngine() {
        engine {
            this@authenticatedRequestsEngine.install(KEY_AUTH_INTERCEPTOR) {
                this@authenticatedRequestsEngine.defaultRequest {
                    parameter(KEY_API_SECRET, BuildKonfig.API_KEY)
                }
            }
        }
    }
I use it to authenticate each request by adding a
parameter
with an
API_KEY
Installs an interceptor defined by block. The key parameter is used as a unique name, that also prevents installing duplicated interceptors.