HI, ```public class HeaderInterceptor implements I...
# multiplatform
d
HI,
Copy code
public class HeaderInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        request = request.newBuilder()
                .addHeader("headerKey0", "HeaderVal0")
                .addHeader("headerKey0", "HeaderVal0--NotReplaced/NorUpdated") //new header added
                .build();

        //alternative
        Headers moreHeaders = request.headers().newBuilder()
                .add("headerKey1", "HeaderVal1")
                .add("headerKey2", "HeaderVal2")
                .set("headerKey2", "HeaderVal2--UpdatedHere") // existing header UPDATED if available, else added.
                .add("headerKey3", "HeaderKey3")
                .add("headerLine4 : headerLine4Val") //line with `:`, spaces doesn't matter.
                .removeAll("headerKey3") //Oops, remove this.
                .build();

        request = request.newBuilder().headers(moreHeaders).build();

        /* ##### List of headers ##### */
        // headerKey0: HeaderVal0
        // headerKey0: HeaderVal0--NotReplaced/NorUpdated
        // headerKey1: HeaderVal1
        // headerKey2: HeaderVal2--UpdatedHere
        // headerLine4: headerLine4Val

        Response response = chain.proceed(request);
        return response;
    }
}
I have something like this custom Interceptor in my Android retrofit interceptor for headers, I am converting this logic to ktor and want add an interceptor there, I could not find a proper solution, the way ktor docs suggest is we need to create a custom feature (Plugin) and install it while instantiating the client, any help or direction is appreciated
m
You can use
defaultRequest
to add headers https://ktor.io/docs/default-request.html
👍 1
d
@Mayank Any suggestion for response interception ?
m
If you want to do just the validation then you can use HttpResponseValidator https://ktor.io/docs/response-validation.html For other purposes a plugin (previously Feature) needs to be created. For reference on how to do that for response, refer https://github.com/ktorio/ktor/blob/60506aafaf8437fefa706438606ed18147624a26/ktor-[…]nt-core/common/src/io/ktor/client/features/HttpCallValidator.kt