【问题标题】:Caching response data with retrofit2+okhttp3使用 retrofit2+okhttp3 缓存响应数据
【发布时间】:2016-06-29 18:05:42
【问题描述】:

我在网络请求中使用带有 okhttp_3 库的 retrofit_2 (beta4)。我需要在网络关闭并且应用程序必须显示上次相同请求的响应数据的情况下缓存响应数据。我发现的所有解决此问题的指南都使用 okhttp lib(不是 okhttp_3)。 我试图解决问题:

public class ApiFactory  {

private static final int CONNECT_TIMEOUT = 45;
private static final int WRITE_TIMEOUT = 45;
private static final int READ_TIMEOUT = 45;
private static final long CACHE_SIZE = 10 * 1024 * 1024; // 10 MB

private static OkHttpClient.Builder clientBuilder;
static {
    clientBuilder = new OkHttpClient
            .Builder()
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
            .cache(new Cache(MyApp.getInstance().getCacheDir(), CACHE_SIZE)) // 10 MB
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    if (MyApp.getInstance().isNetwConn()) {
                        request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
                    } else {
                        request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
                    }
                    return chain.proceed(request);
                }
            });
}

@NonNull
public static ApiRequestService getApiRequestService() {
    return getRetrofitDefault().create(ApiRequestService.class);
}

@NonNull
private static Retrofit getRetrofitDefault() {
    return new Retrofit.Builder()
            .baseUrl(NetworkUrls.URL_MAIN)
            .addConverterFactory(GsonConverterFactory.create())
            .callbackExecutor(Executors.newFixedThreadPool(5))
            .callbackExecutor(Executors.newCachedThreadPool())
            .callbackExecutor(new Executor() {
                private final Handler mHandler = new Handler(Looper.getMainLooper());

                @Override
                public void execute(Runnable command) {
                    mHandler.post(command);
                }
            })
            .client(clientBuilder.build())
            .build();
}
}

但这不起作用。所有请求在网络开启时都能正常工作,但在网络关闭时不会返回缓存数据。请帮忙解决这个问题。

【问题讨论】:

  • 任何更新?...等待解决方案。

标签: android retrofit2 okhttp3


【解决方案1】:

用作

File cacheDir = new File(MyApplication.getContext().getCacheDir(), cache);
        myCache= new Cache(cacheDir, cacheSize);

        okHttpClient = new OkHttpClient();
        okHttpClient.setCache(myCache);

【讨论】:

  • okhttp3中不存在这样的方法(okHttpClient.setCache)
【解决方案2】:

你必须使用Builder

OkHttpClient client = new OkHttpClient.Builder()
                .cache(cache).build();

【讨论】:

    【解决方案3】:

    您可能还需要在拦截器中重置响应头。

    okhttp3.Response originalResponse = chain.proceed(request);
    if (NetUtils.hasNetwork(mContext)) {
        //when the network is available, you use the '@Headers' cache time in the interface
        String cacheControl = request.cacheControl().toString();
        int maxAge = 60; // read from cache for 1 minute
        return originalResponse.newBuilder()
                .header("Cache-Control", cacheControl)
                //.header("Cache-Control", "public, max-age=" + maxAge)
                .removeHeader("Progma")
                .build();
    } else {
        return originalResponse.newBuilder()
                .header("Cache-Control", "public, only-if-cached, max-stale=2419200") //60 * 60 * 24 * 28 4weeks
                .removeHeader("Pragma")
                .build();
    }
    

    【讨论】:

    • 不幸的是,它不起作用,因为没有缓存数据,当网络关闭时。
    猜你喜欢
    • 2018-01-09
    • 2017-10-28
    • 2018-06-08
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    相关资源
    最近更新 更多