gpt4 book ai didi

android - Retrofit with OKHttp 在离线时如何使用缓存数据

转载 作者:可可西里 更新时间:2023-11-01 18:45:11 24 4
gpt4 key购买 nike

我想用 OkHttp 在没有互联网时使用缓存进行改造。

我这样准备 OkHttpClient:

    RestAdapter.Builder builder= new RestAdapter.Builder()
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json;versions=1");
if (MyApplicationUtils.isNetworkAvaliable(context)) {
int maxAge = 60; // read from cache for 1 minute
request.addHeader("Cache-Control", "public, max-age=" + maxAge);
} else {
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
request.addHeader("Cache-Control",
"public, only-if-cached, max-stale=" + maxStale);
}
}
});

像这样设置缓存:

   Cache cache = null;
try {
cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
} catch (IOException e) {
Log.e("OKHttp", "Could not create http cache", e);
}

OkHttpClient okHttpClient = new OkHttpClient();
if (cache != null) {
okHttpClient.setCache(cache);
}

我检查了 root 设备,在缓存目录中正在保存带有“响应 header ”和 Gzip 文件的文件。

但我没有从离线改造缓存中得到正确答案,尽管在 GZip 文件中编码了我的正确答案。那么我怎样才能让 Retrofit 可以读取 GZip 文件,他怎么知道它应该是哪个文件(因为我有一些文件和其他响应)?

最佳答案

我的公司也有类似的问题:)

问题出在服务器端。在服务器响应中,我有:

Pragma: no-cache

所以当我删除它时,一切都开始工作了。在我删除它之前,我总是遇到这样的异常:504 Unsatisfiable Request (only-if-cached)

好的,那么我这边的实现情况如何。

    OkHttpClient okHttpClient = new OkHttpClient();

File httpCacheDirectory = new File(appContext.getCacheDir(), "responses");

Cache cache = new Cache(httpCacheDirectory, maxSizeInBytes);
okHttpClient.setCache(cache);

OkClient okClient = new OkClient(okHttpClient);

RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setEndpoint(endpoint);
builder.setClient(okClient);

如果您在测试哪一方有问题(服务器或应用程序)时遇到问题。您可以使用此类功能来设置从服务器接收的 header 。

private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control",
String.format("max-age=%d", 60))
.build();
}
};

然后简单地添加它:

okHttpClient.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);

多亏了你所看到的,我能够在测试时删除 Pragma: no-cache header 。

此外,我建议您阅读有关 Cache-Control header 的信息:

max-age , max-stale

其他有用的链接:

List of HTTP header fields

Cache controll

Another sample code

关于android - Retrofit with OKHttp 在离线时如何使用缓存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31321963/

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