【问题标题】:How can i skip okhttp cache and get the response and cache the new response我如何跳过 okhttp 缓存并获取响应并缓存新响应
【发布时间】:2023-04-10 10:54:01
【问题描述】:

我正在为我的网络调用使用带有 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);

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

【问题讨论】:

标签: android retrofit2 okhttp3


【解决方案1】:

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

 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);
    }
}

【讨论】:

    猜你喜欢
    • 2016-08-03
    • 2018-06-19
    • 2016-02-18
    • 2018-07-17
    • 2018-02-11
    • 2016-03-20
    • 2015-05-21
    • 2015-07-05
    • 1970-01-01
    相关资源
    最近更新 更多