retrofit2:添加RequestInterceptor

时间:2016-05-21 22:34:51

标签: java android retrofit2

伙计们,我们正在尝试从改造1 升级到改造2 ,但我很难为所有请求添加请求拦截器。 在改造1 中,我通过做这样的事情实现了它;

public static <S> S createService(Class<S> serviceClass, final String token) {
    RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(Constant.APP_URL);
    builder.setRequestInterceptor(new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
            request.addHeader("token", token);
        }
    });
    RestAdapter adapter = builder.build();

    return adapter.create(serviceClass);
}

但我只是无法在改造2 中解决这个问题......请问有没有人解决我的问题?

1 个答案:

答案 0 :(得分:0)

在依赖项块中添加:

compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'

Retrofit服务类中添加:

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build();

然后添加:

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .client(client) // this is the line you care about
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(JacksonConverterFactory.create())
            .build();