OkHttp 根据服务器返回的的过期时间设置缓存

据返回的缓存时间来缓存响应,可以通过使用OkHttp的CacheControlResponseCacheInterceptor来实现。以下是一个示例代码:

java 复制代码
// 创建缓存目录和缓存对象
File cacheDirectory = new File(context.getCacheDir(), "http-cache");
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(cacheDirectory, cacheSize);

// 创建OkHttpClient实例,并添加自定义的ResponseCacheInterceptor
OkHttpClient client = new OkHttpClient.Builder()
        .cache(cache)
        .addNetworkInterceptor(new ResponseCacheInterceptor())
        .build();

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

        if (originalResponse.isSuccessful()) {
            // 获取服务器返回的缓存相关信息
            String cacheControl = originalResponse.header("Cache-Control");
            String expires = originalResponse.header("Expires");

            // 根据缓存相关信息判断是否需要缓存
            boolean shouldCache = shouldCacheResponse(cacheControl, expires);

            if (shouldCache) {
                // 设置缓存的有效期为服务器返回的缓存时间
                CacheControl cacheControlHeader = new CacheControl.Builder()
                        .maxAge(getMaxAge(cacheControl))
                        .build();

                // 构建新的响应并返回
                Response cachedResponse = originalResponse.newBuilder()
                        .header("Cache-Control", cacheControlHeader.toString())
                        .build();

                return cachedResponse;
            }
        }

        return originalResponse;
    }
}

// 判断是否应该缓存响应的方法
private boolean shouldCacheResponse(String cacheControl, String expires) {
    if (cacheControl == null && expires == null) {
        return false;
    }

    // 判断缓存控制头中是否包含no-store、no-cache指令
    if (cacheControl != null && (cacheControl.contains("no-store") || cacheControl.contains("no-cache"))) {
        return false;
    }

    // 判断过期时间是否已过期
    if (expires != null) {
        try {
            Date expirationDate = HttpDate.parse(expires);
            Date currentDate = new Date();

            if (expirationDate != null && expirationDate.before(currentDate)) {
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    return true;
}

// 获取缓存的最大有效时间
private int getMaxAge(String cacheControl) {
    if (cacheControl != null) {
        CacheControl cc = CacheControl.parse(cacheControl);
        return cc.maxAgeSeconds();
    }

    return -1;
}

在上述示例中,我们创建了一个自定义的ResponseCacheInterceptor拦截器,并将其添加到OkHttpClient中。该拦截器会在每次网络请求返回响应后进行处理。

在拦截器中,我们从服务器的响应中获取Cache-ControlExpires头部信息,并使用shouldCacheResponse()方法判断是否需要缓存响应。如果需要缓存,我们根据服务器返回的缓存时间构建新的响应,并设置对应的Cache-Control头部,然后返回新的响应。

相关推荐
ofoxcoding4 天前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
NeilYuen4 天前
gRPC结合FAISS构建AI助手语义缓存模块(一):设计
人工智能·缓存·faiss
taocarts_bidfans4 天前
反向海淘跨境缓存架构优化:taocarts Redis分层缓存实战技术
redis·缓存·架构·反向海淘·taocarts
退休倒计时4 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
炘爚4 天前
Linux——Redis
数据库·redis·缓存
朝星4 天前
Android开发[14]:网络优化之OkHttp
android·okhttp·kotlin
小挪号底迪滴4 天前
Redis 和 MySQL 数据不一致怎么办?缓存更新策略实战
redis·mysql·缓存
闪电悠米4 天前
黑马点评-Redis ZSet-实现关注 Feed 流
服务器·网络·数据库·redis·缓存·junit·lua
Saniffer_SH5 天前
【高清视频】Gen6 服务器还没到,Gen6 SSD 怎么测?Emily 现场演示三种测试环境
人工智能·驱动开发·测试工具·缓存·fpga开发·计算机外设·压力测试