Retrofit 2 - Elegant way of adding headers in the api level

后端 未结 2 646
轻奢々
轻奢々 2021-01-31 05:28

My Retrofit 2 (2.0.2 currently) client needs to add custom headers to requests.

I\'m using an Interceptor to add these headers to all request

2条回答
  •  一整个雨季
    2021-01-31 06:17

    Maybe you can do that by creating different Retrofit object factory method like this.

    public class RestClient {
        public static  S createService(Class serviceClass) {
            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
            OkHttpClient client = httpClient.build();
    
            Retrofit retrofit = new Retrofit.Builder().baseUrl(APIConfig.BASE_URL)
                    .client(client)
                    .build();
            return retrofit.create(serviceClass);
        }
    
        public static  S createServiceWithAuth(Class serviceClass) {
            Interceptor interceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    final Request request = chain.request().newBuilder()
                            .addHeader("CUSTOM_HEADER_NAME_1", "CUSTOM_HEADER_VALUE_1")
                            .addHeader("CUSTOM_HEADER_NAME_2", "CUSTOM_HEADER_VALUE_2")
                            .build();
    
                    return chain.proceed(request);
                }
            };
            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
            httpClient.addInterceptor(interceptor);
            OkHttpClient client = httpClient.build();
    
            Retrofit retrofit = new Retrofit.Builder().baseUrl(APIConfig.BASE_URL)
                    .client(client)
                    .build();
            return retrofit.create(serviceClass);
        }
    }
    

    if you want to call api without header auth, you can just call createService method:

    YourApi api = RestClient.createService(YourApi.class);
    

    And use createServiceWithAuth method if you want to call api with authentication:

    YourApiWithAuth api = RestClient.createServiceWithAuth(YourApiWithAuth.class);
    

提交回复
热议问题