How to use interceptor to add headers in Retrofit 2.0?

Our team decides to adopt Retrofit 2.0, and I am doing some initial research on this. I am new to this library.

I am wondering how to use interceptor to add custom headers via Retrofits 2.0 to our Android app. There are many guides to using interceptor to add headers in Retrofit 1.X, but since the APIs have changed a lot in the latest version, I'm not sure how to adapt these methods in the new version. In addition, Retrofit has not yet updated its new documentation.

For example, in the following codes, how do I implement the Interceptor class to add additional headers? Also, what exactly is an undocumented Chain object ? When will intercept() be called?

  OkHttpClient client = new OkHttpClient(); client.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response response = chain.proceed(chain.request()); // How to add extra headers? return response; } }); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_API_URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build(); 
+70
java android retrofit
Oct 06 '15 at 6:43
source share
5 answers

Check this.

 public class HeaderInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); request = request.newBuilder() .addHeader("appid", "hello") .addHeader("deviceplatform", "android") .removeHeader("User-Agent") .addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0") .build(); Response response = chain.proceed(request); return response; } } 

Kotlin

 class HeaderInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response = chain.run { proceed( request() .newBuilder() .addHeader("appid", "hello") .addHeader("deviceplatform", "android") .removeHeader("User-Agent") .addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0") .build() ) } } 
+82
Oct. 06 '15 at 6:50
source share

Another alternative to the accepted answer

 public class HeaderInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); request = request.newBuilder() .addHeader("headerKey0", "HeaderVal0") .addHeader("headerKey0", "HeaderVal0--NotReplaced/NorUpdated") //new header added .build(); //alternative Headers moreHeaders = request.headers().newBuilder() .add("headerKey1", "HeaderVal1") .add("headerKey2", "HeaderVal2") .set("headerKey2", "HeaderVal2--UpdatedHere") // existing header UPDATED if available, else added. .add("headerKey3", "HeaderKey3") .add("headerLine4 : headerLine4Val") //line with `:`, spaces doesn't matter. .removeAll("headerKey3") //Oops, remove this. .build(); request = request.newBuilder().headers(moreHeaders).build(); /* ##### List of headers ##### */ // headerKey0: HeaderVal0 // headerKey0: HeaderVal0--NotReplaced/NorUpdated // headerKey1: HeaderVal1 // headerKey2: HeaderVal2--UpdatedHere // headerLine4: headerLine4Val Response response = chain.proceed(request); return response; } } 
+16
Oct. 10 '15 at 9:42
source share
  public class ServiceFactory { public static ApiClient createService(String authToken, String userName, String password) { OkHttpClient defaultHttpClient = new OkHttpClient.Builder() .addInterceptor( chain -> { Request request = chain.request().newBuilder() .headers(getJsonHeader(authToken)) .build(); return chain.proceed(request); }) .authenticator(getBasicAuthenticator(userName, password)) .build(); return getService(defaultHttpClient); } private static Headers getJsonHeader(String authToken) { Headers.Builder builder = new Headers.Builder(); builder.add("Content-Type", "application/json"); builder.add("Accept", "application/json"); if (authToken != null && !authToken.isEmpty()) { builder.add("X-MY-Auth", authToken); } return builder.build(); } private static Authenticator getBasicAuthenticator(final String userName, final String password) { return (route, response) -> { String credential = Credentials.basic(userName, password); return response.request().newBuilder().header("Authorization", credential).build(); }; } private static ApiClient getService(OkHttpClient defaultHttpClient) { return new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(defaultHttpClient) .build() .create(ApiClient.class); } } 
+3
May 13 '16 at 12:11
source share

check basic authentication in Android entries, they use interceptors and this is pretty clear.

https://futurestud.io/blog/android-basic-authentication-with-retrofit

+2
Apr 01 '16 at 18:35
source share

You can use headers with Interceptors using built-in methods like

  interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); Request.Builder builder = original.newBuilder(); builder.header("Authorization","Bearer "+ LeafPreference.getInstance(context).getString(LeafPreference.TOKEN)); Request request = builder.method(original.method(), original.body()) .build(); Log.e("request",request.urlString()); Log.e("header",request.header("Authorization")); return chain.proceed(request); } }); } 
0
Mar 30 '17 at 10:01
source share



All Articles