How to add http interceptor in retrofit in a service generator class

此生再无相见时 提交于 2019-12-11 07:20:13

问题


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?


回答1:


You need to use the http client created when building the retrofit instance.

Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(httpClient)  // This is the line
                .addConverterFactory(GsonConverterFactory.create());



回答2:


I have a Creator class like this

class Creator {
    public static Services newServices() {
        final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        final OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();

        final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Services.HOST)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(GsonUtils.get()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(Services.class);
    }
}


来源:https://stackoverflow.com/questions/54033743/how-to-add-http-interceptor-in-retrofit-in-a-service-generator-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!