Retrofit2 SocketTimeOutException

时间:2017-12-13 03:34:07

标签: android retrofit2 socket-timeout-exception

我为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的子类,为什么我的代码无法捕获它。 我该如何解决这个问题。

2 个答案:

答案 0 :(得分:3)

使用OkHttpClient获取更多配置,例如:

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);

答案 1 :(得分:2)

您可以使用改装回调方法轻松处理改装调用期间发生的异常。它有onResponse()和onFailure()覆盖方法。 如果改装调用成功,则onResponse()将触发,如果调用失败或发生任何异常,则onFailure()将触发。

您可以参考下面的教程,以便更好地了解改装回拨

https://www.journaldev.com/13639/retrofit-android-example-tutorial https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/