How to dynamically set a list of headers in Retrofit 2 (Android)

We are trying to switch to using Retrofit2, and I am having problems with the requirement when we need to pass in a set of dynamically generated headers (used for analytics) for each request.

@Headers is not supported at the parameter level, and since the header field name depends on the current activity, I cannot use @Header.

Is there a way to add headers just before execute ()? (Looking for something similar to @ QueryMap / @ FieldMap, but for headers)

NOTE. I do not have a list of headers when initializing the client (and therefore, it cannot use the Interceptor for this).

+5
source share
1 answer

You can still (and should) use the Interceptor.
All you need is a little Architecture.

First, create an assistant that provides the necessary headers.

public class AnalyticsHeader { private String analyticsHeaderName; private String analyticsHeaderValue; public void setHeaderValue(String header) { this.analyticsHeaderValue = header; } public void setHeaderName(String header) { this.analyticsHeaderName = header; } public String getHeaderName() { return analyticsHeaderName; } public String getHeaderValue() { return analyticsHeaderValue; } } 

Keep an instance of this class in an accessible place inside your application, for example MainActivity of our application (or even better, use Injection Dependency)

Now, after creating the Interceptor, just pass the instance of AnalyticsHeader to the Interceptor:

 public static final class AnalyticsInterceptor implements Interceptor { private final AnalyticsHeader header; public AnalyticsInterceptor(AnalyticsHeader header) { this.header = header; } @Override public Response intercept(Chain chain) throws IOException { final Request original = chain.request(); Response response; if (header.getHeader() != null) { Request request = original.newBuilder() .header(header.getHeaderName(), header.getHeaderValue()) .method(original.method(), original.body()) .build(); response = chain.proceed(request); } else { response = chain.proceed(original); } return response; } } 

And then...

 OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.addInterceptor(new AnalyticsInterceptor(CentralPlaceInApp.getAnalyticsHeader()); ... retrofit = new Retrofit.Builder() .baseUrl(config.getRestUrl()) .client(builder.build()) .build(); 

Now you can change the value of the header at any time during the execution of the application using CentralPlaceInApp.getAnalyticsHeader().setHeaderValue(CurrentActivity.class.getSimpleName());

+2
source

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


All Articles