Hackjustu Hackjustu - 1 year ago 266
Java Question

How to use interceptor to add Headers in Retrofit 2.0

Our team decide to adopt Retrofit 2.0 and I'm doing some initial research on it. I'm a newbie to this library and hope to get some help from the community:)

As stated in the title, I'm wondering how to use

to add customized headers via Retrofits 2.0 in our Android app. There are many tutorials about using
to add headers in Retrofit 1.X, but since the APIs have changed a lot in the latest version, I'm not sure how to adapt those methods in the new version. Also, Retrofit hasn't update its new documentation yet.

For example, in the following codes, how should I implement the
class to add extra headers? Besides, what exactly is the undocumented
? When will the
be called?

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());

// How to add extra headers?

return response;

Retrofit retrofit = new Retrofit.Builder()

Could anyone share some idea on this issue?



Check this out.

public class HeaderInterceptor
        implements Interceptor {
    public Response intercept(Chain chain)
            throws IOException {
        Request request = chain.request();
        request = request.newBuilder()
                .addHeader("appid", "hello")
                .addHeader("deviceplatform", "android")
                .addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
        Response response = chain.proceed(request);
        return response;