Okhttp - OkHttpClient 2.0.0无法解析方法拦截器()

时间:2016-01-09 06:57:15

标签: android retrofit okhttp

我使用Retrofit 1.9.0和OkHttp 2.0.0

compile 'com.squareup.okhttp:okhttp:2.0.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'

但是找不到拦截器方法

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(50000, TimeUnit.MILLISECONDS);
client.setReadTimeout(50000, TimeUnit.MILLISECONDS);
client.interceptor().add(...); // cannot resolve method interceptor

我正在处理这篇文章中建议的改造重试请求 How to retry HTTP requests with OkHttp/Retrofit?

我在这里错过了一些图书馆吗?

2 个答案:

答案 0 :(得分:6)

尝试这样:

compile 'com.google.code.gson:gson:2.5'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
compile 'com.squareup.okhttp3:okhttp:3.0.1'

在您的客户端类中:

OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(
                    new Interceptor() {
                        @Override
                        public Response intercept(Interceptor.Chain chain) throws IOException {
                            Request request = requestBuilder.build();
                            return chain.proceed(request);
                        }
                    })
            .build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    restAPI = retrofit.create(RestAPI.class);

答案 1 :(得分:1)

另外恕我直言使用改装2.0(虽然它仍处于测试阶段,在我看来它足够成熟)。你可以

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:retrofit-converters:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'

同样适用于1.9和2,我发现有一系列优秀的博客可以帮助我更好地学习Retrofit。你可以找到它们here

编辑:由于Retrofit 2依赖OkHttp进行网络操作,因此一旦添加了retrofit2,就不需要显式添加OkHttp依赖项