OkHttp3 缓存不生效

说明

明明自己加了缓存,但是缓存就是不生效!
添加缓存的方法可参照:OkHttp3 Cache - 简书 (jianshu.com) 这篇文章。

问题

配置了明明不生效,经过源神大佬的点播,断点之后发现这块代码:GitHub

  fun invalidatesCache(method: String): Boolean = (method == "POST" ||
      method == "PATCH" ||
      method == "PUT" ||
      method == "DELETE" ||
      method == "MOVE") // WebDAV

调用地方在:GitHub

  internal fun put(response: Response): CacheRequest? {
    val requestMethod = response.request.method

    // 检查协议是否支持缓存
    if (HttpMethod.invalidatesCache(response.request.method)) {
      try {
        remove(response.request)
      } catch (_: IOException) {
        // The cache cannot be written.
      }
      return null
    }
}

调用入口:GitHub

  @Throws(IOException::class)
  override fun intercept(chain: Interceptor.Chain): Response {
    if (cache != null) {
      if (response.promisesBody() && CacheStrategy.isCacheable(response, networkRequest)) {
        // Offer this request to the cache.
        // ⬇️ 检查接口是否支持缓存,不支持返回null
        val cacheRequest = cache.put(response)
        return cacheWritingResponse(cacheRequest, response).also {
          if (cacheResponse != null) {
            // This will log a conditional cache miss only.
            listener.cacheMiss(call)
          }
        }
      }

      // 再次检查
      if (HttpMethod.invalidatesCache(networkRequest.method)) {
        try {
          cache.remove(networkRequest)
        } catch (_: IOException) {
          // The cache cannot be written.
          // 缓存不能存储
        }
      }
     // ....
  }

解决

其实没有解决,解决的办法就是让服务器端的接口换成GET方式,
如果强行加缓存的话还是比较麻烦的,可以参照GitHub这里的官方处理缓存的方法进行添加。
我自己也尝试添加了一下没有加动,主要是https证书缓存时的代码太复杂。

结束

看样子缓存只能存储GET类型的方法。问题终结!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容