Dynamically adding headers in request, working with Rest (Android, Retrofit, OkHTTP)

Hello!

Today I want to tell about one trick in Retrofit.

What do I mean, when I say “Dynamically adding headers”?

Some time ago, I tried to make request to Rest server. But I did not know what headers I’m going to add to the request from time to time.

If you work with Retrofit, you know, that first we must to create interface with some methods. Something like this:

public interface RestApi{
@Headers({“Accept: application/vnd.github.v3.full+json”,”User-Agent: Retrofit-Sample-App”})
@GET(“widget/list”)
Call<List<Widget>> widgetList();
}

As you can see, we must to add Headers across special annotation. And we must do it for every header. It is not good idea, when you don’t know what kind of headers you are going to add from time to time.

After some search I found interesting thing. We can add to our Retrofit another okHttp module, and use its advantages.

In app.gradle:

compile (‘com.squareup.retrofit2:retrofit:2.0.0-beta4’)
{
// exclude Retrofit’s OkHttp peer-dependency module and define your own module import
exclude module: ‘okhttp’
}
compile ‘com.squareup.okhttp3:okhttp:3.0.0’

This step will allow us to add headers dynamically with help of okHttp client. First, we need to build our own okHttp client. Something like this:

OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); 
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder();

//Here we add our collection of headers (HashMap more useful (= )
for (ArrayList<String> item : headers) {
builder.addHeader(item.get(0), item.get(1));
}
Request request = builder.build(); 
Response response = chain.proceed(request); // Customize or return the response
return response;
}
});
OkHttpClient client = httpClient.build();

Second, we adding our client to Retrofit builder:

Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).client(client).build(); 
RestApi service = retrofit.create(RestApi.class);

Third, just call our method.

Interceptors — is really cool thing. I want to know more about it in near time.

Hope, it helps!

Kind regards.


Originally published at junior-freelancer.weebly.com.