Adding header to all request with Retrofit 2

Ashkan Sarlak picture Ashkan Sarlak · Sep 16, 2015 · Viewed 108.9k times · Source

Retrofit 2's documentation says:

Headers that need to be added to every request can be specified using an OkHttp interceptor.

It can be done easily using the previous version, here's the related QA.

But using retrofit 2, I couldn't find something like setRequestInterceptor or setInterceptor method that can be applied to Retrofit.Builder object.

Also it seems that there's no RequestInterceptor in OkHttp anymore. Retrofit's doc refers us to Interceptor that I didn't quite understand how to use it for this purpose.

How can I do this?

Answer

dtx12 picture dtx12 · Sep 16, 2015
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

httpClient.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request().newBuilder().addHeader("parameter", "value").build();
        return chain.proceed(request);
    }
});
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(url).client(httpClient.build()).build();