简体   繁体   English

使用 okhttp3 检查并恢复缓存文件

[英]Check and recover a cached file with okhttp3

I am using okhttp3 to make requests to the server, not using retrofit.我正在使用 okhttp3 向服务器发出请求,而不是使用改造。 My idea is to make a call and save the response in cache for 15 minutes.我的想法是拨打电话并将响应保存在缓存中 15 分钟。 if during those 15 minutes, the request is made again, recover the cache response, after 15 minutes, request it again from the server.如果在这 15 分钟内再次发出请求,则恢复缓存响应,15 分钟后,再次从服务器请求。

This is my code:这是我的代码:

public class Handler_JSON_get {

    public Handler_JSON_get() {

    }

    public String makeServiceCall(String url, JSONObject data) {
        final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

        Cache cache = new Cache(new File(Environment.getExternalStorageDirectory().getPath() + "/Android/data/MY_PACKAGE/", "cache"), 10 * 1024 * 1024);

        OkHttpClient okHttpClient;

            Log.i("2134","Usando caché");
             okHttpClient = new OkHttpClient.Builder()
                    .addNetworkInterceptor(provideCacheInterceptor())
                    .readTimeout(45, TimeUnit.SECONDS)
                    .protocols(Arrays.asList(Protocol.HTTP_1_1))
                    .addInterceptor(provideCacheInterceptor())
                    .cache(cache)
                    .build();

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        try {
            Response response = okHttpClient.newCall(request).execute();

            Log.i(TAG,"Response:"+response.code());

            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    Interceptor provideCacheInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());
                CacheControl cacheControl = new CacheControl.Builder()
                        .maxAge(15, TimeUnit.MINUTES)
                        .build();

                return response.newBuilder()
                        .header("cache", cacheControl.toString())
                        .build();
            }
        };
    }
}

The problem is that he always makes the call to the server and I have many doubts.问题是他总是打电话给服务器,我有很多疑问。

okhttp3 is responsible for seeing if there is a cached response in the storage? okhttp3 负责查看存储中是否有缓存响应?

The call saves a journal file, is this the correct file?调用保存了一个日志文件,这是正确的文件吗?

What am I missing or what am I doing wrong?我错过了什么或我做错了什么?

I have seen that there are quite a few questions about it, but I can not make those answers compatible with my code.我已经看到有很多关于它的问题,但我无法使这些答案与我的代码兼容。

I would sincerely appreciate the parts that are necessary in my code to function properly, I start to go crazy.我真诚地感谢我的代码中正常运行所必需的部分,我开始发疯了。

Thanks in advance.提前致谢。

It took me some time to spot it : The correct header name is Cache-Control , not cache :我花了一些时间才发现它:正确的标头名称是Cache-Control ,而不是cache

return response.newBuilder()
                    .header("Cache-Control", cacheControl.toString())
                    .build();

Also it seems that adding the interceptor with addNetworkInterceptor is sufficient, it is not necessary to also add it with addInterceptor另外似乎用addNetworkInterceptor添加拦截器就足够了,没有必要也用addInterceptor添加它

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

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