让OkHttp3 也能缓存Post 请求

http://blog.csdn.net/qq_34308476/article/details/67632078

让OkHttp3 也能缓存Post 请求

转载 2017年03月28日 09:43:34
  

让OkHttp3 也能缓存Post 请求

标签: OKHttp3OKHttp3缓存Post请求OKHttp3只能缓存Get请求OKHttp3缓存
 分类:

OkHttp越来越受欢迎,而且缓存机制使用起来非常方便。但是有一个问题,OkHttp3只能缓存Get请求,无奈我们的服务端大部分请求都是Post处理的,只好把OkHttp3的源码稍微改一改,先用起来再说吧!(虽然破坏了规则)

我们只需要注释两处代码就能避开只缓存Get请求的限制:

第一处,在Cache.Java中。

 

[java] view plain copy
 
 
  1. private CacheRequest put(Response response) {  
  2.     String requestMethod = response.request().method();  
  3.   
  4.   //modify by yuanye  注释 只有GET请求才缓存的限制  
  5. //    if (HttpMethod.invalidatesCache(response.request().method())) {  
  6. //      try {  
  7. //        remove(response.request());  
  8. //      } catch (IOException ignored) {  
  9. //        // The cache cannot be written.  
  10. //      }  
  11. //      return null;  
  12. //    }  
  13.        
  14. //    if (!requestMethod.equals("GET")) {  
  15. //      // Don't cache non-GET responses. We're technically allowed to cache  
  16. //      // HEAD requests and some POST requests, but the complexity of doing  
  17. //      // so is high and the benefit is low.  
  18. //      return null;  
  19. //    }  
  20.   
  21.     if (HttpHeaders.hasVaryAll(response)) {  
  22.       return null;  
  23.     }  
  24.   
  25.     Entry entry = new Entry(response);  
  26.     DiskLruCache.Editor editor = null;  
  27.     try {  
  28.       editor = cache.edit(urlToKey(response.request()));  
  29.       if (editor == null) {  
  30.         return null;  
  31.       }  
  32.       entry.writeTo(editor);  
  33.       return new CacheRequestImpl(editor);  
  34.     } catch (IOException e) {  
  35.       abortQuietly(editor);  
  36.       return null;  
  37.     }  
  38.   }  

第二处,在Request.java中:

 

 

[java] view plain copy
 
 
 在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:14px;">public Builder method(String method, RequestBody body) {  
  2.       if (method == null) throw new NullPointerException("method == null");  
  3.       if (method.length() == 0) throw new IllegalArgumentException("method.length() == 0");  
  4.       if (body != null && !HttpMethod.permitsRequestBody(method)) {  
  5.         throw new IllegalArgumentException("method " + method + " must not have a request body.");  
  6.       }  
  7.       //modify by yuanye  由于post请求也做缓存,从缓存创建的request会默认使用GET,然后将body置空,此时这里的检测会必出错  
  8. //      if (body == null && HttpMethod.requiresRequestBody(method)) {  
  9. //        throw new IllegalArgumentException("method " + method + " must have a request body.");  
  10. //      }  
  11.       this.method = method;  
  12.       this.body = body;  
  13.       return this;  
  14.     }</span>  


 

需要注意的是:缓存时,会将请求的url作为key来关联缓存文件。如果你的post请求url一致,而参数是通过post提交的,这样就会导致不同的请求当成一个请求来缓存。

有问题请留言。

 
 
posted @ 2017-12-27 14:40  sky20080101  阅读(302)  评论(0)    收藏  举报