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!
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();
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With