首页 > 解决方案 > 我如何跳过 okhttp 缓存并获取响应并缓存新响应

问题描述

我正在为我的网络调用使用带有 okHTTP 缓存的 Retrofit,当我收到响应时,我编写了一个拦截器来查找响应正文“timeToCache”值并重新写入缓存标头。当我更新实体并调用 get 方法时,我现在面临一个问题,它总是向我返回缓存响应。为了避免我在请求中添加了以下标头

@GET("ws/something")
Something getSomething(@Header("Cache-Control") String cacheControl);
and then when calling you either supply null for a (maybe-)cached version or "no-cache" for a live version:

myApi.getSomething(forceRefresh ? "no-cache" : null);

现在我得到了新的响应,但是这个响应没有得到缓存?我现在如何将此响应保存到缓存?

标签: androidretrofit2okhttp3

解决方案


我找不到更好的方法来解决这个问题,所以我实现了删除缓存条目方法来在更新事件成功后删除条目。

 public void removeHTTPCacheEntry(final String cachedDelURL) {
    try {
        if (client != null && client.cache() != null && client.cache().urls() != null) {



            Iterator<String> cacheURlsItr = client.cache().urls();
            while (cacheURlsItr.hasNext()) {
                try {
                    URL cachedURL = new URL(cacheURlsItr.next());

                    String urlPath = cachedURL == null ? "" : cachedURL.getPath();


                    if (!StringUtils.isEmpty(urlPath) && cachedDelURL.equals(urlPath)) {
                        cacheURlsItr.remove();

                        break;
                    }
                } catch (MalformedURLException e1) {
                    Log.e(TAG, "MalformedURLException", e1);

                }
            }
        }
    } catch (IOException e1) {
        Log.e(TAG, "removeHTTPCacheEntry", e1);
    }
}

推荐阅读