I created a separate service generator class as shown is this guide https://futurestud.io/tutorials/retrofit-2-manage-request-headers-in-okhttp-interceptor
ApiServiceGenerator.java
public class ApiServiceGenerator {
private static final String BASE_URL = "http://192.168.0.205/hadia/api/";
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
private static OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
public static <S> S createService(
Class<S> serviceClass) {
return retrofit.create(serviceClass);
}
}
i need to add an Authorization Header to each request, how do i do that using this static createService method?
Here is how to create an Interceptor for adding header to each request
httpClient.addInterceptor(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("Authorization", "auth-value"); // <-- this is the important line
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
How i add this method to add a Bearer token to each request?