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();

Blow 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("https://10.0.2.2:3000/") .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()); Retrofit retrofit = builder.build();

coma

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.

Mrunal

Tech Expert

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

The founder's survey report on "What Matters For Startup" is released - Get your copy and learn the trends of successful companies :)

Download Free eBook Now!

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

"Mindbowser was very helpful with explaining the development process and started quickly on the project."

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

"The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs."

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

"They're very tech-savvy, yet humble."

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

"Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier"

author
Katie Taylor
Founder, Child Life On Call
coma

“As a founder of a budding start up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity."

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give