android - 我如何跳过 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);
现在我得到了新的响应,但是这个响应没有得到缓存?我现在如何将此响应保存到缓存?
解决方案
我找不到更好的方法来解决这个问题,所以我实现了删除缓存条目方法来在更新事件成功后删除条目。
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);
}
}
推荐阅读
- java - 从动作监听器设置按钮的文本
- android - 如何在 Android Studio 中为三星 Galaxy Note plus 和 Google Pixel XL3 创建单独的值文件夹
- julia - 通过数组维度广播
- django - 如何加密身份验证模型中的 django 用户名字段?
- pandas - 将 Pandas 浮点格式从点更改为逗号
- json - 在Json Python2.7中每个键的开头添加一个#
- ios - iOS 13 和 14 上的 NSKeyValuePopPendingNotificationLocal 崩溃
- sql - 使用 sql 计算进行的总预订和收集的总金额
- google-chrome - 如何确定连接的主机与 Chrome 中的请求 URL 不同的原因?
- c# - Unicode 转义序列