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