gpt4 book ai didi

java - okhttp缓存:how to get cache data first then get network data in network connetting?

转载 作者:行者123 更新时间:2023-11-30 06:10:31 26 4
gpt4 key购买 nike

引用:https://github.com/square/okhttp/issues/4003

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

我正在尝试这样:

 @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;
}

最佳答案

尝试使用 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()

关于java - okhttp缓存:how to get cache data first then get network data in network connetting?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50341923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com