How to add multiple headers with an Http window

I am using Retrofit 2 and Okhttp for my Android project. I want to add some headers to the api request.

This is my interceptor code:

public class NetworkInterceptors implements Interceptor { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Userid", "10034") .addHeader("Securitykey", "Fb47Gi") .build(); return chain.proceed(request); } } 

This does not work properly. On the server side, I get only the last header added (in the above example, I only get the Securitykey missing "Userid")

Please, help.

+5
source share
2 answers

Thanks for the support. I found the answer, this works great for me.

 public class NetworkInterceptors implements Interceptor { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request request = chain.request(); Request newRequest; newRequest = request.newBuilder() .addHeader("Userid", "10034") .addHeader("Securitykey", "Fb47Gi") .build(); return chain.proceed(newRequest); } } 
+3
source

You can use this class to convey context in this class if the user is already logged in.

  public class ApiClient { public static final String BASE_URL = ""; private static Retrofit retrofit = null; static Context mcontext; public static Retrofit getClient(Context context,String baseUrl) { mcontext = context; OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(220, TimeUnit.SECONDS)// Set connection timeout .readTimeout(220, TimeUnit.SECONDS)// Read timeout .writeTimeout(220, TimeUnit.SECONDS)// Write timeout .addInterceptor( HeaderInterceptor() ) // .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)// Add cache interceptor // .cache(cache)// Add cache .build(); Gson gson = new GsonBuilder() .setLenient() .create(); if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); } return retrofit; } private static Interceptor HeaderInterceptor() { return new Interceptor() { @Override public okhttp3.Response intercept(Chain chain) throws IOException { okhttp3.Request request = chain.request(); if(SharedPreference.getlogin(mcontext).equals("")){ request = request.newBuilder() .addHeader("Accept", "application/json") .addHeader("Authorization", "Bearer "+SharedPreference.gettoken(mcontext)) .build(); } else { request = request.newBuilder() .addHeader("Accept", "application/json") .build(); } okhttp3.Response response = chain.proceed(request); return response; } }; } } 
0
source

Source: https://habr.com/ru/post/1244236/


All Articles