Retrofit and Okhttp dynamically add headers and parameters for each Request (5), and retrofitokhttp
Header
How to Add header to Every Request
Add unified general headers without overwriting the previous Headers
okHttpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request original = chain.request(); // Request customization: add request headers Request.Builder requestBuilder = original.newBuilder() .addHeader("header-key", "value1") .addHeader("header-key", "value2"); Request request = requestBuilder.build(); return chain.proceed(request); }});
Add a uniform General header that overwrites the preceding header.
okHttpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request original = chain.request(); // Request customization: add request headers Request.Builder requestBuilder = original.newBuilder() .header("headerkey", "header-value"); // <-- this is the important line Request request = requestBuilder.build(); return chain.proceed(request); }});
Parameters
How to Add Query Parameters to Every Request
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();httpClient.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); HttpUrl originalHttpUrl = original.url(); HttpUrl url = originalHttpUrl.newBuilder() .addQueryParameter("apikey", "your-actual-api-key") .build(); // Request customization: add request headers Request.Builder requestBuilder = original.newBuilder() .url(url); Request request = requestBuilder.build(); return chain.proceed(request); }});