让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提交的,这样就会导致不同的请求当成一个请求来缓存。

有问题请留言。


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值