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());
source share