https://kotlinlang.org logo
#android
Title
# android
t

Tuan Kiet

07/04/2019, 5:56 AM
is there any Interceptor equivalent in Ktor like OkHttp?
t

tseisel

07/04/2019, 6:57 AM
When configuring Ktor
HttpClient
with the OkHttp engine, you have the opportunity to configure OkHttp to use interceptors.
t

Tuan Kiet

07/04/2019, 8:13 AM
what about other platform?
d

Dias

07/04/2019, 8:57 AM
I haven't used OkHttp, but I assume interceptor is something like a ktor client feature that can intercept calls at various stages
t

tseisel

07/04/2019, 9:39 AM
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

Tobi

07/04/2019, 2:22 PM
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.
65 Views