如何从Web服务器缓存okHTTP响应? [英] How to cache okHTTP response from Web server?

查看:87
本文介绍了如何从Web服务器缓存okHTTP响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何缓存来自Web服务器(返回json数据)的okHTTP响应?

I want to know how can okHTTP response from Web server (which returns json data) be cached?

我希望我的应用程序下载RecycleView所需的所有数据,并在用户首次运行该应用程序后将其缓存-避免重新下载和解析来自Web服务器的所有相同数据(如果数据未更改).

I want my app to download all the data needed for RecycleView and cache it once the user runs the app first time - and avoid re-downloading and parsing all the same data from Web server, if data has not changed.

我试图获取响应头,但这就是我得到的:

I tried to get response headers, but this is what I get:

Request URL: https://somedomain.com/wp-json/?categories=3&per_page=100&status=publish
Request Method: GET
Status Code: 200 OK
Remote Address: 176.28.12.139:443
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages
Allow: GET
Connection: keep-alive
Content-Encoding: gzip
Content-Type: application/json; charset=UTF-8
Date: Fri, 23 Mar 2018 15:41:23 GMT
Link: <https://somedomain.com/wp-json/>; rel="https://api.w.org/"
Server: nginx
Transfer-Encoding: chunked
Vary: Accept-Encoding
X-Content-Type-Options: nosniff
X-Powered-By: PleskLin
X-Powered-By: PHP/7.1.15
X-Robots-Tag: noindex
X-WP-Total: 43
X-WP-TotalPages: 1
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: hr,en-US;q=0.9,en;q=0.8,de;q=0.7,nb;q=0.6
Connection: keep-alive
Host: somedomain.com
Referer: https://somedomain.com/somedir/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
categories: 3
per_page: 100
status: publish

我已阅读到我可以从服务器响应中找到 ETAG或上次修改,以检查是否有任何更改,但是正如您所看到的那样,没有这样的事情.

I have read that I could find ETAG or Last-Modified from the Server response to check for any changes, but as you can see there is no such thing.

您是否知道如果应用程序仅在第一次运行时才需要下载数据,然后才更改数据,该怎么办?

Do you have any idea what to do if app only needs to download data at the first run - and after that only if the data has changed?

推荐答案

您需要这样的缓存拦截器:

You need cache interceptor like this:

public class CacheInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());

        CacheControl cacheControl = new CacheControl.Builder()
                .maxAge(15, TimeUnit.MINUTES) // 15 minutes cache
                .build();

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

使用 Cache 将此拦截器添加到您的 OkHttpClient 中,如下所示:

Add this interceptor with Cache to your OkHttpClient like this:

File httpCacheDirectory = new File(applicationContext.getCacheDir(), "http-cache");
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(httpCacheDirectory, cacheSize);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addNetworkInterceptor(new CacheInterceptor())
            .cache(cache)
            .build();

这篇关于如何从Web服务器缓存okHTTP响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆