Android Retrofit2 Retrofit with OkHttp interceptor


This example shows how to use a request interceptor with OkHttp. This has numerous use cases such as:

  • Adding universal header to the request. E.g. authenticating a request
  • Debugging networked applications
  • Retrieving raw response
  • Logging network transaction etc.
  • Set custom user agent
Retrofit.Builder builder = new Retrofit.Builder()

if (!TextUtils.isEmpty(githubToken)) {
    // `githubToken`: Access token for GitHub
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request newReq = request.newBuilder()
                    .addHeader("Authorization", format("token %s", githubToken))
            return chain.proceed(newReq);



See OkHttp topic for more details.