Retrofit Interceptor Add Authorization Token
1 min readApr 13, 2018
Add customized headers via Retrofits 2.0 in our Android app. There are many tutorials about using interceptor
to add headers in Retrofit. You can add authorization token and also you can write a logic for token regeneration
compile "com.squareup.retrofit2:retrofit:2.3.0"
compile "com.squareup.retrofit2:converter-gson:2.3.0"
You can easily intercept the request on the network layer provided by OkHttp
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("User-Agent", "Your-App-Name")
.header("Accept", "application/vnd.yourapi.v1.full+json")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
You can add authenticator in the request and you can also write a logic of token regeneration process