如何使用Retrofit2服务获得对OkHttp客户端的引用?

时间:2018-07-25 19:52:15

标签: android retrofit retrofit2 okhttp okhttp3

我正在使用Retrofit2从服务器获取数据,并且正在处理nasty OkHttp bug,导致URL上的java.net.SocketTimeoutException通常可以访问。原来在ConnectionPool中有一些死掉的客户端,当client.connectionPool().evictAll()发生异常时,我想将其驱逐出去。

但是,我不确定如何访问OkHttp客户端:

try {
    Response<Listing> response = MainApplication.apiProvider.getApiA().getListing(arg).execute();
    if(isResponseOk(response)) {
        ...
    }
} catch (SocketTimeoutException ex) {
    // get the OkHttp client and call connectionPool().evictAll()
}

MainApplication.apiProvider.getApiA()仅返回对API服务的引用,其创建方式如下:

Retrofit.Builder builder = new Retrofit.Builder()
                        .baseUrl("https://api.xyz.com")
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create());

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS);
httpClient.writeTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS);
httpClient.readTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS);
httpClient.followSslRedirects(true);

OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(MyApiProvider.class);

编辑: 也许我应该使用OkHttp's Interceptor(但仍然如何获得客户?):

httpClient.addNetworkInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response response = null;
                try {
                    response = chain.proceed(request);
                } catch (SocketTimeoutException ex) {
                    // again,how to access client? httpClient.build() is called later
                } catch (IOException ex) {
                    throw  ex;
                }
                return response;
            }
        })

0 个答案:

没有答案