Skip to main content

Posts

Showing posts from February, 2021

How to create an OkHttp interceptor and why do you need one?

An http interceptor can become handy if you need to log all your requests or add a bearer token to every request when calling a protected resource with an access token in OAuth 2.0 . To create an interceptor you basically need to create an OkHttpClient by calling the OkHttpClient Builder and add an interceptor to it. OkHttpClient okHttpClient = new OkHttpClient.Builder() You can have access to the current request by calling chain.request(). Once you get the request you can then add or build on top of it by adding an additional header to send your Bearer Token. Request auth_request = chain.request() The last step is to return a Response object by calling chain.proceed, passing the new request. return chain.proceed(auth_request); And the final code: OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request auth_request = cha