Adding a header to all queries using Retrofit 2

Retrofit documentation 2 :

Headers that must be added to each request can be specified using the OkHttp interceptor.

This can be easily done using a previous version related to QA.

But using modification 2, I could not find something like the setRequestInterceptor or setInterceptor method, which can be applied to the Retrofit.Builder object.

It also seems that there is no RequestInterceptor in OkHttp . "Retrofitting a document" refers to Interceptor , which I did not quite understand how to use it for this purpose.

How can i do this?

+107
java android header retrofit
Sep 16 '15 at 10:12
source share
9 answers
 OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder().addHeader("parameter", "value").build(); return chain.proceed(request); } }); Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(url).client(httpClient.build()).build(); 
+170
Sep 16 '15 at 11:05
source share

The latest version of retrofitting → 2.1.0.

lambda version:

  builder.addInterceptor(chain -> { Request request = chain.request().newBuilder().addHeader("key", "value").build(); return chain.proceed(request); }); 

ugly long version:

  builder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder().addHeader("key", "value").build(); return chain.proceed(request); } }); 

full version:

 class Factory { public static APIService create(Context context) { OkHttpClient.Builder builder = new OkHttpClient().newBuilder(); builder.readTimeout(10, TimeUnit.SECONDS); builder.connectTimeout(5, TimeUnit.SECONDS); if (BuildConfig.DEBUG) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); builder.addInterceptor(interceptor); } builder.addInterceptor(chain -> { Request request = chain.request().newBuilder().addHeader("key", "value").build(); return chain.proceed(request); }); builder.addInterceptor(new UnauthorisedInterceptor(context)); OkHttpClient client = builder.build(); Retrofit retrofit = new Retrofit.Builder().baseUrl(APIService.ENDPOINT).client(client).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); return retrofit.create(APIService.class); } } 

gradle (you need to add a registration interceptor if you plan to use it):

  //----- Retrofit compile 'com.squareup.retrofit2:retrofit:2.1.0' compile "com.squareup.retrofit2:converter-gson:2.1.0" compile "com.squareup.retrofit2:adapter-rxjava:2.1.0" compile 'com.squareup.okhttp3:logging-interceptor:3.4.0' 
+69
Jan 26 '16 at 21:23
source share

To register your request and response, you need an interceptor, and to configure the header, you need an interceptor, here is a solution for adding an interceptor at the same time using modification 2.1

  public OkHttpClient getHeader(final String authorizationValue ) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient okClient = new OkHttpClient.Builder() .addInterceptor(interceptor) .addNetworkInterceptor( new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request request = null; if (authorizationValue != null) { Log.d("--Authorization-- ", authorizationValue); Request original = chain.request(); // Request customization: add request headers Request.Builder requestBuilder = original.newBuilder() .addHeader("Authorization", authorizationValue); request = requestBuilder.build(); } return chain.proceed(request); } }) .build(); return okClient; } 

Now in your modified object add this header in the client

 Retrofit retrofit = new Retrofit.Builder() .baseUrl(url) .client(getHeader(authorizationValue)) .addConverterFactory(GsonConverterFactory.create()) .build(); 
+11
Aug 23 '16 at 7:27
source share

I found another way for Retrofit 1.9 and 2.0, for the Json content type.

 @Headers({"Accept: application/json"}) @POST("user/classes") Call<playlist> addToPlaylist(@Body PlaylistParm parm); 

You can add many more headers, i.e.

 @Headers({ "Accept: application/json", "User-Agent: Your-App-Name", "Cache-Control: max-age=640000" }) 
+8
Mar 27 '18 at 19:11
source share

In my case, addInterceptor() did not work to add HTTP headers to my request, I had to use addNetworkInterceptor() . The code is as follows:

 OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addNetworkInterceptor(new AddHeaderInterceptor()); 

And interceptor code:

 public class AddHeaderInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request.Builder builder = chain.request().newBuilder(); builder.addHeader("Authorization", "MyauthHeaderContent"); return chain.proceed(builder.build()); } } 

These and other examples on this essence.

+5
Aug 11 '16 at 12:04 on
source share

If you use the addInterceptor method to add an HttpLoggingInterceptor, it will not log things added by other hooks used later by the HttpLoggingInterceptor.

For example: if you have two "HttpLoggingInterceptor" and "AuthInterceptor" interceptors, and the HttpLoggingInterceptor is applied first, then you cannot view the http-params or the headers set by AuthInterceptor.

 OkHttpClient.Builder builder = new OkHttpClient.Builder() .addNetworkInterceptor(logging) .addInterceptor(new AuthInterceptor()); 

I solved this using the addNetworkInterceptor method.

+4
Jun 30 '17 at 12:47 on
source share

Use this modified client

 class RetrofitClient2(context: Context) : OkHttpClient() { private var mContext:Context = context private var retrofit: Retrofit? = null val client: Retrofit? get() { val logging = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY) val client = OkHttpClient.Builder() .connectTimeout(Constants.TIME_OUT, TimeUnit.SECONDS) .readTimeout(Constants.TIME_OUT, TimeUnit.SECONDS) .writeTimeout(Constants.TIME_OUT, TimeUnit.SECONDS) client.addInterceptor(logging) client.interceptors().add(AddCookiesInterceptor(mContext)) val gson = GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create() if (retrofit == null) { retrofit = Retrofit.Builder() .baseUrl(Constants.URL) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client.build()) .build() } return retrofit } } 



I pass the JWT along with every request. Please do not pay attention to variable names, this is a little confusing.

 class AddCookiesInterceptor(context: Context) : Interceptor { val mContext: Context = context @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val builder = chain.request().newBuilder() val preferences = CookieStore().getCookies(mContext) if (preferences != null) { for (cookie in preferences!!) { builder.addHeader("Authorization", cookie) } } return chain.proceed(builder.build()) } } 
+1
Jan 08 '19 at 9:46
source share

In kotlin, adding an interceptor looks like this:

 .addInterceptor{ it.proceed(it.request().newBuilder().addHeader("Cache-Control", "no-store").build())} 
0
Sep 20 '19 at 13:31 on
source share

The kotlin RetrofitHelper library allows you to make API calls using a few lines of code.

Add headers to your application class as follows:

 class Application : Application() { override fun onCreate() { super.onCreate() retrofitClient = RetrofitClient.instance //api url .setBaseUrl("https://reqres.in/") //you can set multiple urls // .setUrl("example","http://ngrok.io/api/") //set timeouts .setConnectionTimeout(4) .setReadingTimeout(15) //enable cache .enableCaching(this) //add Headers .addHeader("Content-Type", "application/json") .addHeader("client", "android") .addHeader("language", Locale.getDefault().language) .addHeader("os", android.os.Build.VERSION.RELEASE) } companion object { lateinit var retrofitClient: RetrofitClient } } 

And then call:

 retrofitClient.Get<GetResponseModel>() //set path .setPath("api/users/2") //set url params Key-Value or HashMap .setUrlParams("KEY","Value") // you can add header here .addHeaders("key","value") .setResponseHandler(GetResponseModel::class.java, object : ResponseHandler<GetResponseModel>() { override fun onSuccess(response: Response<GetResponseModel>) { super.onSuccess(response) //handle response } }).run(this) 

See the documentation for more information .

0
Sep 30 '19 at 2:10
source share



All Articles