讓OkHttp3 也能緩存Post 請求

OkHttp越來越受歡迎,而且緩存機制使用起來非常方便。但是有一個問題,OkHttp3只能緩存Get請求,無奈我們的服務端大部分請求都是Post處理的,只好把OkHttp3的源碼稍微改一改,先用起來再說吧!(雖然破壞了規則)

我們只需要註釋兩處代碼就能避開只緩存Get請求的限制:

第一處,在Cache.java中。

private CacheRequest put(Response response) {
    String requestMethod = response.request().method();

  //modify by yuanye  註釋 只有GET請求才緩存的限制
//    if (HttpMethod.invalidatesCache(response.request().method())) {
//      try {
//        remove(response.request());
//      } catch (IOException ignored) {
//        // The cache cannot be written.
//      }
//      return null;
//    }
     
//    if (!requestMethod.equals("GET")) {
//      // Don't cache non-GET responses. We're technically allowed to cache
//      // HEAD requests and some POST requests, but the complexity of doing
//      // so is high and the benefit is low.
//      return null;
//    }

    if (HttpHeaders.hasVaryAll(response)) {
      return null;
    }

    Entry entry = new Entry(response);
    DiskLruCache.Editor editor = null;
    try {
      editor = cache.edit(urlToKey(response.request()));
      if (editor == null) {
        return null;
      }
      entry.writeTo(editor);
      return new CacheRequestImpl(editor);
    } catch (IOException e) {
      abortQuietly(editor);
      return null;
    }
  }

第二處,在Request.java中:

public Builder method(String method, RequestBody body) {
      if (method == null) throw new NullPointerException("method == null");
      if (method.length() == 0) throw new IllegalArgumentException("method.length() == 0");
      if (body != null && !HttpMethod.permitsRequestBody(method)) {
        throw new IllegalArgumentException("method " + method + " must not have a request body.");
      }
      //modify by yuanye  由於post請求也做緩存,從緩存創建的request會默認使用GET,然後將body置空,此時這裏的檢測會必出錯
//      if (body == null && HttpMethod.requiresRequestBody(method)) {
//        throw new IllegalArgumentException("method " + method + " must have a request body.");
//      }
      this.method = method;
      this.body = body;
      return this;
    }


需要注意的是:緩存時,會將請求的url作爲key來關聯緩存文件。如果你的post請求url一致,而參數是通過post提交的,這樣就會導致不同的請求當成一個請求來緩存。

有問題請留言。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章