An http interceptor can become handy if you need to log all your requests or add a bearer token to every request when calling a protected resource with an access token in OAuth 2.0.
To create an interceptor you basically need to create an OkHttpClient by calling the OkHttpClient Builder and add an interceptor to it.
You can have access to the current request by calling chain.request(). Once you get the request you can then add or build on top of it by adding an additional header to send your Bearer Token.
The last step is to return a Response object by calling chain.proceed, passing the new request.
And the final code:
Retrofit
If you have been using Retrofit as a wrapper on top of OkHttp to make http requests you can easily add your new interceptor to it by calling the client method of the Retrofit Builder like this:
To create an interceptor you basically need to create an OkHttpClient by calling the OkHttpClient Builder and add an interceptor to it.
OkHttpClient okHttpClient = new OkHttpClient.Builder()
You can have access to the current request by calling chain.request(). Once you get the request you can then add or build on top of it by adding an additional header to send your Bearer Token.
Request auth_request = chain.request()
The last step is to return a Response object by calling chain.proceed, passing the new request.
return chain.proceed(auth_request);
And the final code:
OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request auth_request = chain.request() .newBuilder() .addHeader("Authorization", "Bearer " + YOUR_ACCESS_TOKEN) .build(); return chain.proceed(auth_request); } }).build();
Retrofit
If you have been using Retrofit as a wrapper on top of OkHttp to make http requests you can easily add your new interceptor to it by calling the client method of the Retrofit Builder like this:
return new Retrofit.Builder() .baseUrl(YOUR_BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build() .create(YOUR_RETROFIT_INTERFACE.class);So now every time you call your Retrofit interface method to make an http request, OkHttp will intercept your call and add a bearer token to your request header.
Comments
Post a Comment