简体   繁体   English

OkHttp响应缓存不起作用

[英]OkHttp Response caching not works

in my android application I am using retrofit for making network download, also I am using OkHttp to cache the response, given below is the code that I wrote 在我的android应用程序中,我正在使用改造进行网络下载,我也在使用OkHttp来缓存响应,以下是我编写的代码

 private RestAdapter buildRestAdapter(String baseUrl, Context ctx) {
    RestAdapter.LogLevel logLevel = RestAdapter.LogLevel.FULL;
    RestAdapter.Builder builder = new RestAdapter.Builder();
    builder.setLogLevel(logLevel);

    if (!TextUtils.isEmpty(baseUrl))
        builder.setEndpoint(baseUrl);

    builder.setRequestInterceptor(new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
            int maxStale = 60 * 60 * 24 * 28;
            request.addHeader("Cache-Control",
                    "public, only-if-cached, max-stale=" + maxStale);
        }
    });

    File httpCacheDirectory = new File(ctx.getCacheDir(), "responses");
    Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
    OkHttpClient okHttpClient = new OkHttpClient();

    if (cache != null) {
        okHttpClient.setCache(cache);
    }
    builder.setClient(new OkClient(okHttpClient));
    return builder.build();
}

the problem here is when I am making an API call I'm getting failure response and the Error says 504 Unsatisfiable Request (only-if-cached) 这里的问题是当我进行API调用时,我得到失败响应,并且错误显示504 Unsatisfiable Request (only-if-cached)无法满足的504 Unsatisfiable Request (only-if-cached)

what could be the issue here ? 这里可能是什么问题? any help will be appreciated 任何帮助将不胜感激

By having "only-if-cached" in the Cache-Control directive the client won't contact the server, it's just going to check the cache and return the 504 when it cannot find a cache entry match. 通过在Cache-Control指令中使用“仅缓存”,客户端将不会与服务器联系,它将仅检查缓存并在找不到匹配的缓存项时返回504。

How to solve it? 怎么解决呢?

Handling the 504 response with a new request without the client's Cache-Control header. 使用没有客户端的Cache-Control标头的新请求处理504响应。 Or just removing the "only-if-cached" if it's not the intented behaviour. 或者,如果不是预期的行为,则仅删除“仅当缓存”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM