OkHttp越来越受欢迎,而且缓存机制使用起来非常方便。但是有一个问题,OkHttp3只能缓存Get请求,无奈我们的服务端大部分请求都是Post处理的,只好把OkHttp3的源码稍微改一改,先用起来再说吧!(虽然破坏了规则)
我们只需要注释两处代码就能避开只缓存Get请求的限制:
第一处,在Cache.Java中。
- private CacheRequest put(Response response) {
- String requestMethod = response.request().method();
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 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中:
- <span style="font-size:14px;">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.");
- }
-
-
-
-
- this.method = method;
- this.body = body;
- return this;
- }</span>
需要注意的是:缓存时,会将请求的url作为key来关联缓存文件。如果你的post请求url一致,而参数是通过post提交的,这样就会导致不同的请求当成一个请求来缓存。
有问题请留言。