我使用 Retrofit 2 库和 okhttp3 在我的 Android 应用程序中进行 API 调用。我需要在某些操作后使某些特定网址的缓存无效(创建新帖子后使获取帖子无效)。
在互联网上每个人都说我需要获取缓存迭代器并通过调用remove()方法来删除url,但没有人展示如何正确地做到这一点。我正在尝试以这种方式从缓存中删除第一个网址:
Cache.urls().next().remove()
但是因为 urls() 方法是非静态的,所以它不起作用。我也不知道如何获取 okhttp 缓存实例。当我尝试时
Cache cache = new Cache(this.getCacheDir(), 10000);
cache.urls().next();
在MainActivity
内部,这次我得到了java.util.NoSuchElementException
。
Failed to load DynamiteLoader: java.lang.NullPointerException: Attempt to invoke interface method 'android.os.IBinder com.google.android.gms.dynamic.IObjectWrapper.asBinder()' on a null object reference
09-17 11:37:38.868 21171-21171/com.elmxana.elmxana E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.elmxana.elmxana, PID: 21171
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.elmxana.elmxana/com.elmxana.elmxana.MainActivity}: java.util.NoSuchElementException
您能帮我找到使特定网址的缓存无效的确切解决方案吗?
最佳答案
可以使用 url 迭代器删除单个项目。这在用户通过拉动刷新类型操作启动强制刷新后很常见。
val urlIterator = cache.urls()
while (urlIterator.hasNext()) {
if (urlIterator.next().startsWith("https://www.google.com/")) {
urlIterator.remove()
}
}
引用:https://square.github.io/okhttp/caching/#pruning-the-cache
关于java - 如何从 okhttp 的缓存中删除 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46262028/