记录一下知识点(http://www.51testing.com/html/28/116228-238337.html)
Cache-Control | 条件GET请求 | no-cache | only-if-cached |
---|---|---|---|
Cache-Control: max-age=31536000, public | 服务器返回:Last-Modified | 不使用缓存 | 只使用缓存 |
max-age是有效期 | 请求带上:If-Modified-Since | 不命中返回503错误/网络错误 | |
服务器返回:ETag | |||
请求带上:If-None-Match |
条件GET请求用法:
服务器返回
Last-Modified: Sat, 4 Aug 2017 09:31:27 GMT
再次请求带上
If-Modified-Since: Sat, 4 Aug 2017 09:31:27 GMT
服务器会进行判断,缓存可用就只会返回304
服务器返回
ETag: "1090c1ef-8603"
再次请求带上
If-None-Match:"1090c1ef-8603"
服务器会进行判断,缓存可用就只会返回304
下面请开始你的表演
还记得上次的源码分析的拦截器链吗,一条完整的拦截器链如下
见名思义,我们去看CacheIntercept
// 缓存
final InternalCache cache;
public CacheInterceptor(InternalCache cache) {
this.cache = cache;
}
@Override public Response intercept(Chain chain) throws IOException {
// 本次请求的缓存
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
long now = System.currentTimeMillis();
// 缓存策略,符合上图的缓存机制。最重要就是里面的get方法。就好像一棵决策树,输入请求和缓存响应,输出决策后的请求和缓存响应
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
if (cache != null) {
cache.trackResponse(strategy);
}
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
// 和上图所说的只使用缓存并且没有缓存命中,返回504
// If we're forbidden from using the network and the cache is insufficient, fail.
if (networkRequest == null && cacheResponse == null) {
return new Response.Builder()
.request(chain.request())
.protocol(Protocol.HTTP_1_1)
.code(504)
.message("Unsatisfiable Request (only-if-cached)")
.body(Util.EMPTY_RESPONSE)
.sentRequestAtMillis(-1L)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
}
// 符合缓存条件,直接使用缓存
// If we don't need the network, we're done.
if (networkRequest == null) {
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
}
// 继续往下调用拦截器链,进行网络请求
Response networkResponse = null;
try {
networkResponse = chain.proceed(networkRequest);
} finally {
// If we're crashing on I/O or otherwise, don't leak the cache body.
if (networkResponse == null && cacheCandidate != null) {
closeQuietly(cacheCandidate.body());
}
}
// Etag或者Last-Modified
// If we have a cache response too, then we're doing a conditional get.
if (cacheResponse != null) {
// 服务器返回304,数据无改变,即可用本地缓存,然后更新一下信息即可
if (networkResponse.code() == HTTP_NOT_MODIFIED) {
Response response = cacheResponse.newBuilder()
.headers(combine(cacheResponse.headers(), networkResponse.headers()))
.sentRequestAtMillis(networkResponse.sentRequestAtMillis())
.receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
networkResponse.body().close();
// Update the cache after combining headers but before stripping the
// Content-Encoding header (as performed by initContentStream()).
cache.trackConditionalCacheHit();
cache.update(cacheResponse, response);
return response;
} else {
closeQuietly(cacheResponse.body());
}
}
Response response = networkResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
// 如果设置了缓存
if (cache != null) {
// 缓存有内容且能够缓存(通过header、剩余空间等等来判断)
if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
// Offer this request to the cache.
// 存入缓存,注意这里的put里面也是有判断的,只有符合的缓存条件的才会缓存,别以为到put了就一定缓存了(例如post请求不缓存)。
CacheRequest cacheRequest = cache.put(response);
return cacheWritingResponse(cacheRequest, response);
}
// 对缓存再进行判断
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
cache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
}
return response;
}
接下来看缓存策略的get方法
public CacheStrategy get() {
CacheStrategy candidate = getCandidate();
if (candidate.networkRequest != null && request.cacheControl().onlyIfCached()) {
// 不命中缓存且只使用缓存
// We're forbidden from using the network and the cache is insufficient.
return new CacheStrategy(null, null);
}
return candidate;
}
/** Returns a strategy to use assuming the request can use the network. */
private CacheStrategy getCandidate() {
// No cached response.
// 没有缓存
if (cacheResponse == null) {
return new CacheStrategy(request, null);
}
// 这个不知道,缺少必要的握手
// Drop the cached response if it's missing a required handshake.
if (request.isHttps() && cacheResponse.handshake() == null) {
return new CacheStrategy(request, null);
}
// 该请求不应该被缓存...
// If this response shouldn't have been stored, it should never be used
// as a response source. This check should be redundant as long as the
// persistence store is well-behaved and the rules are constant.
if (!isCacheable(cacheResponse, request)) {
return new CacheStrategy(request, null);
}
// 不使用缓存或者header带etag或者if-modify-since
CacheControl requestCaching = request.cacheControl();
if (requestCaching.noCache() || hasConditions(request)) {
return new CacheStrategy(request, null);
}
// 下面是判断缓存是否失效吧
long ageMillis = cacheResponseAge();
long freshMillis = computeFreshnessLifetime();
if (requestCaching.maxAgeSeconds() != -1) {
freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));
}
long minFreshMillis = 0;
if (requestCaching.minFreshSeconds() != -1) {
minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
}
long maxStaleMillis = 0;
CacheControl responseCaching = cacheResponse.cacheControl();
if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
}
if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
Response.Builder builder = cacheResponse.newBuilder();
if (ageMillis + minFreshMillis >= freshMillis) {
builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");
}
long oneDayMillis = 24 * 60 * 60 * 1000L;
if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
}
return new CacheStrategy(null, builder.build());
}
// 对缓存进行判断是否有etag或者lastModified ,有得话帮你添加header进request
// Find a condition to add to the request. If the condition is satisfied, the response body
// will not be transmitted.
String conditionName;
String conditionValue;
if (etag != null) {
conditionName = "If-None-Match";
conditionValue = etag;
} else if (lastModified != null) {
conditionName = "If-Modified-Since";
conditionValue = lastModifiedString;
} else if (servedDate != null) {
conditionName = "If-Modified-Since";
conditionValue = servedDateString;
} else {
return new CacheStrategy(request, null); // No condition! Make a regular request.
}
Headers.Builder conditionalRequestHeaders = request.headers().newBuilder();
Internal.instance.addLenient(conditionalRequestHeaders, conditionName, conditionValue);
Request conditionalRequest = request.newBuilder()
.headers(conditionalRequestHeaders.build())
.build();
return new CacheStrategy(conditionalRequest, cacheResponse);
}
得出结论表格,和上图缓存策略一致
networkRequest | cacheResponse | result |
---|---|---|
null | null | only-if-cached(表明不进行网络请求,且缓存不存在或者过期,一定会返回503错误) |
null | non-null | 不进行网络请求,而且缓存可以使用,直接返回缓存,不用请求网络 |
non-null | null | 需要进行网络请求,而且缓存不存在或者过期,或者包含If-Modified-Since或者If-None-Match,则直接访问网络 |
non-null | non-null | Header中含有ETag/Last-Modified标签,需要在条件请求下使用,还是需要访问网络 |
结论表格源于作者:BlackSwift
结束啦-----------(对于ok不进行缓存的,下次再说了)