Updated 4 August 2017
Interceptor the team sounds like something which is used in between the source and destination. In another language, an interceptor can hijack HTTP requests before they reach the endpoint.
By the Wikipedia,
In the field of software development, an interceptor pattern is a software design pattern that is used when software systems or frameworks want to offer a way to change, or augment, their usual processing cycle. Key aspects of the pattern are that the change is transparent and used automatically. In essence, the rest of the system does not have to know something has been added or changed and can keep working as before. To facilitate this, a predefined interface for extension has to be implemented, some kind of dispatching mechanism is required where interceptors are registered (this may be dynamic, at runtime, or static, e.g. through configuration files) and context objects are provided, which allow access to the framework’s internal state.
Step 1: Create a retrofit client,
123456789 public static Retrofit getClient(final Context mContext) {retrofit = new Retrofit.Builder().baseUrl(ApplicationConstant.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();}return retrofit;}
Step 2: Create interceptor,
1234 OkHttpClient.Builder oktHttpClient = new OkHttpClient.Builder().connectTimeout(ApplicationConstant.DEFAULT_CONNECT_TIMEOUT_IN_MIN, TimeUnit.MINUTES).writeTimeout(ApplicationConstant.DEFAULT_WRITE_TIMEOUT_IN_MIN, TimeUnit.MINUTES).readTimeout(ApplicationConstant.DEFAULT_READ_TIMEOUT_IN_MIN, TimeUnit.MINUTES);
Step 3: Add interceptor,
1234567891011 oktHttpClient.addInterceptor(new Interceptor() {@Overridepublic Response intercept(Chain chain) throws IOException {Request original = chain.request();Request request = original.newBuilder().header("token", AppSharedPref.getToken(mContext)).method(original.method(), original.body()).build();return chain.proceed(request);}});
Step 4: Add to the retrofit client,
12345 retrofit = new Retrofit.Builder().baseUrl(ApplicationConstant.BASE_URL).addConverterFactory(GsonConverterFactory.create()).client(oktHttpClient.build()) // add this line.build();
Thanks for reading this blog, You have any questions or problems comment below.
Happy Coding. Stay Super.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.