OkHttp Interceptors

During the development of android application, there are some basic things we need to do. The most important part is making the request and getting the appropriate response from the server.
Retrofit is a commonly used type-safe REST client for android and java. Retrofit provides additional functionalities for the custom headers, multiparts request body, file upload and download, mocking responses and many more.
Interceptors and authenticators are one of them.

Why to choose?

retrofit-okhttp
When you need to change something in HTTP requests like change the body of request or manage the response or simply produce the logs which are helpful for debugging, then OkHttp Interceptors is the correct choice.
Using Interceptors, we can monitor, rewrite and retry the network calls. Interceptors are used centrally. Generally we use the loggers to monitor the network calls in each and every request but using interceptor we can add the logger centally, that will work for all network calls. Another advantage of using Interceptor is we can catch the response offline-fir

How interceptors works

Interceptors
When an application makes an HTTP request, the Interceptor modifies the request before it is sent to the server. After that OkHttp send the request to the server, in return the server sends.
Back HTTP response. Before response handled by the retrofit methods, Interceptors act upon the response objects like read or store data and headers then only it will call the callback functions of retrofit like onSuccess(), onFailure().
This is how it simply works.
We will see the most common parts in interceptors i.e adding headers and handling error globally.

Add headers using interceptors

Add the Authorization in the header field is the common example while sending the HTTP request.
If we need the header field with the value in each and every request then we can use the interceptor to add this information.
This way, you need not to add the @Header in every end point declaration. There are two ways to add the headers.  We can override the existing key with the same key or we can add them just without checking them.
Below is the code snippet we can add with overriding header:
OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(new Interceptor() { 

@Override public Response intercept(Interceptor.Chain chain) throws IOException { 

Request original = chain.request(); // Request customization: add request headers 

Request.Builder requestBuilder = original.newBuilder() .header("Authorization", "auth-value"); // <-- this is the important line Request request = requestBuilder.build(); 

return chain.proceed(request); 

}

 });

 OkHttpClient client = httpClient.build();
Below is the code snippet we can add when we have multiple headers with the same key. The method we need to use is .addHeader.
OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(new Interceptor() {

 @Override 

public Response intercept(Interceptor.Chain chain) throws IOException { Request original = chain.request(); // Request customization: add request headers 

Request.Builder requestBuilder = original.newBuilder() .addHeader("Cache-Control", "no-cache") 

.addHeader("Cache-Control", "no-store");

 Request request = requestBuilder.build(); return chain.proceed(request); } }); 

OkHttpClient client = httpClient.build();

Error Handling

Interceptors provide another feature i.e error handling globally. In every request’s response,  we need to handle the error codes. If we use an interceptor then we can have a single place where we can handle major errors.
Advantage of this approach is every request made deals the error in the same way.
OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(new Interceptor() { 

@Override public okhttp3.Response intercept(Chain chain) throws IOException 

{ 

Request request = chain.request(); 

okhttp3.Response response = chain.proceed(request); // todo deal with the issues the way you need to 

if (response.code() == 500) 

{ 

startActivity( new Intent( ErrorHandlingActivity.this, ServerIsBrokenActivity.class ) ); 

return response; 

}

if (response.code() == 401) 

{ 

//Required logic

return response; 

}

if (response.code() == 403) 

{ 

//Required logic

return response; 

}

 return response; 

} 

}) .build(); 




Retrofit.Builder builder = new Retrofit.Builder() .baseUrl("http://10.0.2.2:3000/") .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()); Retrofit retrofit = builder.build();

Conclusion

OkHttp Interceptors provide great methods to handle the app data globally, to log the request and response and also to add the authentication headers. Also we can refresh the token when it will be unauthorised.

subscribe to our newsletter

   
   

About Author

IMG_20200728_113424

Mrunal Joshi

I have been having Android and React Native development experience for more than 2 years. I like to learn new and creative things.
Related Posts

Leave a Comment

A-Complete-Guide-to-Everything-You-Need-to-Know-About-Data-Visualization