Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a replacement for the RequestInterceptor in Retrofit 2?

I ran into a problem that RequestInterceptor has been removed from the Retrofit 2. Earlier, my RestAdapter builder was as follows:

private RestAdapter.Builder getBuilder(RequestInterceptor requestInterceptor) {
    RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(BuildConfig.SERVER_URL)
            .setClient(connectionClient)
            .setRequestInterceptor(requestInterceptor)
            .setConverter(new JacksonConverter());
    return builder;
}

As far as I know, at the moment it's recommended to use interceptor from the OkHttp library instead of the RequestInterceptor.

I couldn't find the exemplary implementation of this approach, therefore, be grateful for any help in this matter.

Thanks!

like image 862
Mark Korzhov Avatar asked Oct 29 '15 18:10

Mark Korzhov


2 Answers

intercepts have to be set through OkHttp in retrofit 2

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(...)

and then register it to Retrofit

Retrofit restAdapter = new Retrofit.Builder()
        .baseUrl(Constants.BASE_URL)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
like image 174
Blackbelt Avatar answered Nov 16 '22 15:11

Blackbelt


Interceptors can be added to client itself.

okHttpClient.interceptors().add(...)

When you are executing this line.You are actually adding your own interceptor into existing list of interceptors already added into client.

You can create your own interceptor

public class HttpLoggingInterceptor implements Interceptor {

private final static String TAG = LogUtils.makeLogTag(HttpLoggingInterceptor.class);

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    LOGD(TAG, "**********************       REQUEST START     **********************");
    LOGD(TAG, "REQUEST URL -> "+request.urlString());
    LOGD(TAG, "REQUEST HEADERS -> "+request.headers());
    LOGD(TAG, "**********************       REQUEST END     **********************");


    Response response = chain.proceed(chain.request());


    LOGD(TAG, "**********************       RESPONSE START     **********************");
    LOGD(TAG, "RESPONSE CODE -> "+response.code());
    LOGD(TAG, "RESPONSE HEADERS -> "+response.headers());
    LOGD(TAG, "**********************       RESPONSE END     **********************");
    return response;
}

}

and then plugin/add it to client any time before building service

public static <S> S createService(Class<S> serviceClass) {
    okHttpClient.interceptors().add(new HttpLoggingInterceptor());
    Retrofit retrofit = builder.client(okHttpClient).build();
    return retrofit.create(serviceClass);
}
like image 3
Gagandeep Singh Avatar answered Nov 16 '22 15:11

Gagandeep Singh