我设置了Retrofit:

private Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetworkUtil.isNetworkAvailable()) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }
            Response response = chain.proceed(request); //Exception here

            if (NetworkUtil.isNetworkAvailable()) {
                String cacheControl = request.cacheControl().toString();
                response = response.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", cacheControl)
                        .build();
            } else {
                int maxStale = 60 * 60 * 24 * 7;
                response = response.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
            }
            return response;
        }
    };

我用来设置缓存:
builder = new OkHttpClient.Builder()
                    .cookieJar(new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(Apploader.context)))
                    .addNetworkInterceptor(interceptor)
                    .addInterceptor(interceptor)
                    .cache(cache)
                    .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

有时服务器响应时间太长,因为SocketTimeOut我的应用程序崩溃

它在行上中断:我评论的Response response = chain.proceed(request);SocketTimeOutIOException的子类,为什么我的代码无法捕获它。
我该如何解决这个问题。

最佳答案

使用OkHttpClient进行更多配置,例如follwing:

final OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .connectTimeout(20, TimeUnit.SECONDS)
    .writeTimeout(20, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .build();

然后将这个okHttpClient设置为RetrofitBuilder
Retrofit.Builder()
    .client(okHttpClient);

08-05 18:47