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

前端 未结 2 543
無奈伤痛
無奈伤痛 2021-01-24 15:12

I created a separate service generator class as shown is this guide https://futurestud.io/tutorials/retrofit-2-manage-request-headers-in-okhttp-interceptor

ApiServiceGen

相关标签:
2条回答
  • 2021-01-24 15:50

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-24 15:53

    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());
    
    0 讨论(0)
提交回复
热议问题