Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Retrofit 2.0 adding headers with interceptor doesn't work

I have Singleton dagger module for OkHttp client and I am trying to add header using Interceptor

@Provides
@Singleton
OkHttpClient provideOkhttpClient(Cache cache, final LocalData localData) {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);

    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(logging);
    client.addNetworkInterceptor(new Interceptor() {
        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder()
                    .addHeader("Hp-Application", "Android");
            Request request = requestBuilder.build();
            Response originalResponse = chain.proceed(request);
            try {
                if (originalResponse.code() == 200) {
                    localData.setLastUpdateTime(System.currentTimeMillis());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return originalResponse;
        }
    });
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.cache(cache);
    return client.build();
}

But looking to the logs I can't see expected header. Also I receive error, as specific call don't work without required header.

I also tried to add it with addInterceptor()/addNetworkInterceptor() using different class

 public class HeaderInterceptor
        implements Interceptor {
    @Override
    public Response intercept(Chain chain)
            throws IOException {
        Request request = chain.request();
        request = request.newBuilder()
                .addHeader("Hp-Application", "Android")
                .build();
        return chain.proceed(request);
    }
}

But this way didn't work for me too.

How can I add this header to each call of application having only one implementation?

like image 734
Igor SKRYL Avatar asked Sep 22 '17 11:09

Igor SKRYL


2 Answers

The order you add the interceptors matters. Your logging interceptor runs first, and only after that is the header-adding interceptor run.

For best logging experience, make the logging interceptor the last one you add.

like image 147
laalto Avatar answered Nov 07 '22 17:11

laalto


Hey @Igor try this snippet this might help

public class RetrofitClient {

    private static String BASE_URL = "http://192.168.0.100/rest/main.php/";
    private static Retrofit retrofit = null;

    public static Retrofit getRetroftInstance() {
        if (retrofit == null) {

            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
            httpClient.addNetworkInterceptor(new SessionRequestInterceptor());
            httpClient.addNetworkInterceptor(new ReceivedCookiesInterceptor());

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient.build())
                    .build();
        }

        return retrofit;
    }}

public class ReceivedCookiesInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());

        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = new HashSet<>();
            for (String header : originalResponse.headers("Set-Cookie")) {
                cookies.add(header);
                if(header.startsWith("XSRF-TOKEN")) {
                    String newCookie[]=header.split(";");
                    System.out.println("newCookie Length: "+newCookie.length);
                    for(String ss:newCookie) {
                        if(ss.startsWith("XSRF-TOKEN")) {
                            System.out.println("Cookies ss: " + ss);
                            sharedPrefs.setToken(ss);
                        }
                    }
                }
            }
        }
        return originalResponse;
    }
}

public class SessionRequestInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();

        Request.Builder request = original.newBuilder();

        request.header("Cookie",ServiceSharedPrefs.getInstance().getToken()));

        request.method(original.method(), original.body());

        return chain.proceed(request.build());
    }

}
like image 45
Piyush Patel Avatar answered Nov 07 '22 17:11

Piyush Patel