okhttp cache:如何首先获取缓存数据然后获取网络连接中的网络数据?

时间:2018-05-15 03:30:59

标签: java okhttp cache-control

REF:https://github.com/square/okhttp/issues/4003

大多数解决方案是网络请求网络,没有网络请求缓存。 我的要求是首先请求缓存,然后请求网络。 THX !!!!

我这样想:

 @Override
public okhttp3.Response intercept(Chain chain) throws IOException {
    //拦截Request对象
    Request request = chain.request();
    //判断有无网络连接
    boolean connected = CommonUtils.isNetConnected();
    if (connected) {
        Response response = chain.proceed(request);
        return response.newBuilder()
                .removeHeader("Pragma")
                .removeHeader("Cache-Control")
                .header("Cache-Control", "public, max-age=" + TIMEOUT_CONNECT)
                .build();
    } else {
        //没有网络
        BeLog.e(TAG, "没有有网络");
        //无网络时强制使用缓存数据
        request = request.newBuilder()
                .cacheControl(CacheControl.FORCE_CACHE)
                .build();
        Response response = chain.proceed(request);
        return response.newBuilder()
                .removeHeader("Pragma")
                .removeHeader("Cache-Control")
                .header("Cache-Control", "public, only-if-cached, max-stale=" + TIMEOUT_DISCONNECT)
                .build();
    }

    //return response;
}

1 个答案:

答案 0 :(得分:1)

尝试使用CacheControl.Builder()。immutable()。build(),例如:

val cacheSize: Long = 10 * 1024 * 1024  // 10 MB
val cache = Cache(applicationContext.cacheDir, cacheSize)

val interceptor = Interceptor { chain ->
    val request: Request? = chain.request()?.newBuilder()?.cacheControl(CacheControl.Builder().immutable().build())?.build()
    chain.proceed(request)
}

val okHttpClient = OkHttpClient.Builder()
    .cache(cache)
    .addInterceptor(interceptor)
    .build()

val builder = Retrofit.Builder()
     .baseUrl("yourBaseUrl")
     .client(okHttpClient)
     .addConverterFactory(GsonConverterFactory.create())

builder.build()