OkHttp3源码详解之HTTP重定向&缓存的处理(二)

}

// If we’re forbidden from using the network and the cache is insufficient, fail.
if (networkRequest == null && cacheResponse == null) {
//强制使用缓存,又找不到缓存,就报不合理请求响应了
userResponse = new Response.Builder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.protocol(Protocol.HTTP_1_1)
.code(504)
.message(“Unsatisfiable Request (only-if-cached)”)
.body(EMPTY_BODY)
.build();
return;
}

//上面情况处理之后,就是使用缓存返回,还是网络请求的情况了

// If we don’t need the network, we’re done.
if (networkRequest == null) {
//使用缓存返回响应
userResponse = cacheResponse.newBuilder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.cacheResponse(stripBody(cacheResponse))
.build();
userResponse = unzip(userResponse);
return;
}

//使用网络请求
//下面就是网络请求流程了,略

}
}

接下来我们分析

  1. Cache是如何获取缓存的。
  2. 缓存策略是如何判断的。
Cache获取缓存

从Cache的get方法开始。它按以下步骤进行。

  1. 计算request对应的key值,md5加密请求url得到。
  2. 根据key值去DiskLruCache查找是否存在缓存内容。
  3. 存在缓存的话,创建缓存Entry实体。ENTRY_METADATA代表响应头信息,ENTRY_BODY代表响应体信息。
  4. 然后根据缓存Entry实体得到响应,其中包含了缓存的响应头和响应体信息。
  5. 匹配这个缓存响应和请求的信息是否匹配,不匹配的话要关闭资源,匹配的话返回。

public final class Cache implements Closeable, Flushable {
//获取缓存
Response get(Request request) {
//计算请求对应的key
String key = urlToKey(request);
DiskLruCache.Snapshot snapshot;
Entry entry;
try {
//这里从DiskLruCache中读取缓存信息
snapshot = cache.get(key);
if (snapshot == null) {
return null;
}
} catch (IOException e) {
// Give up because the cache cannot be read.
return null;
}

try {
//这里读取缓存的响应头信息
entry = new Entry(snapshot.getSource(ENTRY_METADATA));
} catch (IOException e) {
Util.closeQuietly(snapshot);
return null;
}
//然后得到响应信息,包含了缓存响应头和响应体信息
Response response = entry.response(snapshot);
//判断缓存响应和请求是否匹配,匹配url,method,和其他响应头信息
if (!entry.matches(request, response)) {
//不匹配的话,关闭响应体
Util.closeQuietly(response.body());
return null;
}

//返回缓存响应
return response;
}

//这里md5加密url得到key值
private static String urlToKey(Request request) {
return Util.md5Hex(request.url().toString());
}

}

如果存在缓存的话,在指定的缓存目录中,会有两个文件“.0”和“.1”,分别存储某个请求缓存的响应头和响应体信息。(“****”是url的md5加密值)对应的ENTRY_METADATA响应头和ENTRY_BODY响应体。缓存的读取其实是由DiskLruCache来读取的,DiskLruCache是支持Lru(最近最少访问)规则的用于磁盘存储的类,对应LruCache内存存储。它在存储的内容超过指定值之后,就会根据最近最少访问的规则,把最近最少访问的数据移除,以达到总大小不超过限制的目的。

接下来我们分析CacheStrategy缓存策略是怎么判定的。

CacheStrategy缓存策略

直接看CacheStrategy的get方法。缓存策略是由请求和缓存响应共同决定的。

  1. 如果缓存响应为空,则缓存策略为不使用缓存。
  2. 如果请求是https但是缓存响应没有握手信息,同上不使用缓存。
  3. 如果请求和缓存响应都是不可缓存的,同上不使用缓存。
  4. 如果请求是noCache,并且又包含If-Modified-Since或If-None-Match,同上不使用缓存。
  5. 然后计算请求有效时间是否符合响应的过期时间,如果响应在有效范围内,则缓存策略使用缓存。
  6. 否则创建一个新的有条件的请求,返回有条件的缓存策略。
  7. 如果判定的缓存策略的网络请求不为空,但是只使用缓存,则返回两者都为空的缓存策略。

public final class CacheStrategy {

public Factory(long nowMillis, Request request, Response cacheResponse) {
this.nowMillis = nowMillis;
//网络请求和缓存响应
this.request = request;
this.cacheResponse = cacheResponse;

if (cacheResponse != null) {
//找到缓存响应的响应头信息
Headers headers = cacheResponse.headers();
for (int i = 0, size = headers.size(); i < size; i++) {
//查看响应头信息中是否有以下字段信息
String fieldName = headers.name(i);
String value = headers.value(i);
if (“Date”.equalsIgnoreCase(fieldName)) {
servedDate = HttpDate.parse(value);
servedDateString = value;
} else if (“Expires”.equalsIgnoreCase(fieldName)) {
expires = HttpDate.parse(value);
} else if (“Last-Modified”.equalsIgnoreCase(fieldName)) {
lastModified = HttpDate.parse(value);
lastModifiedString = value;
} else if (“ETag”.equalsIgnoreCase(fieldName)) {
etag = value;
} else if (“Age”.equalsIgnoreCase(fieldName)) {
ageSeconds = HeaderParser.parseSeconds(value, -1);
} else if (OkHeaders.SENT_MILLIS.equalsIgnoreCase(fieldName)) {
sentRequestMillis = Long.parseLong(value);
} else if (OkHeaders.RECEIVED_MILLIS.equalsIgnoreCase(fieldName)) {
receivedResponseMillis = Long.parseLong(value);
}
}
}
}

public CacheStrategy get() {
//获取判定的缓存策略
CacheStrategy candidate = getCandidate();

if (candidate.networkRequest != null && request.cacheControl().onlyIfCached()) {
// 如果判定的缓存策略的网络请求不为空,但是只使用缓存,则返回两者都为空的缓存策略。
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.
//如果请求是https,而缓存响应的握手信息为空,则返回没有缓存响应的策略
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);
}

//获取请求头中的CacheControl信息
CacheControl requestCaching = request.cacheControl();
//如果请求头中的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信息
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());
}

//构造一个新的有条件的Request,添加If-None-Match,If-Modified-Since等信息
Request.Builder conditionalRequestBuilder = request.newBuilder();

if (etag != null) {
conditionalRequestBuilder.header(“If-None-Match”, etag);
} else if (lastModified != null) {
conditionalRequestBuilder.header(“If-Modified-Since”, lastModifiedString);
} else if (servedDate != null) {
conditionalRequestBuilder.header(“If-Modified-Since”, servedDateString);
}

Request conditionalRequest = conditionalRequestBuilder.build();
//根据是否有If-None-Match,If-Modified-Since信息,返回不同的缓存策略
return hasConditions(conditionalRequest)
? new CacheStrategy(conditionalRequest, cacheResponse)
: new CacheStrategy(conditionalRequest, null);
}

/**

  • Returns true if the request contains conditions that save the server from sending a response
  • that the client has locally. When a request is enqueued with its own conditions, the built-in
  • response cache won’t be used.
    */
    private static boolean hasConditions(Request request) {
    return request.header(“If-Modified-Since”) != null || request.header(“If-None-Match”) != null;
    }
    }

接来下我们看看CacheControl类里有些什么。

CacheControl

public final class CacheControl {

//表示这是一个优先使用网络验证,验证通过之后才可以使用缓存的缓存控制,设置了noCache
public static final CacheControl FORCE_NETWORK = new Builder().noCache().build();

//表示这是一个优先先使用缓存的缓存控制,设置了onlyIfCached和maxStale的最大值
public static final CacheControl FORCE_CACHE = new Builder()
.onlyIfCached()
.maxStale(Integer.MAX_VALUE, TimeUnit.SECONDS)
.build();

//以下的字段都是HTTP中Cache-Control字段相关的值
private final boolean noCache;
private final boolean noStore;
private final int maxAgeSeconds;
private final int sMaxAgeSeconds;
private final boolean isPrivate;
private final boolean isPublic;
private final boolean mustRevalidate;
private final int maxStaleSeconds;
private final int minFreshSeconds;
private final boolean onlyIfCached;
private final boolean noTransform;

//解析头文件中的相关字段,得到该缓存控制类
public static CacheControl parse(Headers headers) {

}

}

可以发现,它就是用于描述响应的缓存控制信息。

然后我们再看看Okhttp存储缓存是怎么进行的。

Okhttp存储缓存流程

存储缓存的流程从HttpEngine的readResponse发送请求开始的。

public final class HttpEngine {
/**

  • Flushes the remaining request header and body, parses the HTTP response headers and starts
  • reading the HTTP response body if it exists.
    */
    public void readResponse() throws IOException {
    //读取响应,略

// 判断响应信息中包含响应体
if (hasBody(userResponse)) {
// 如果缓存的话,缓存响应头信息
maybeCache();
//缓存响应体信息,同时zip解压缩响应数据
userResponse = unzip(cacheWritingResponse(storeRequest, userResponse));
}
}

// 如果缓存的话,缓存响应头信息
private void maybeCache() throws IOException {
InternalCache responseCache = Internal.instance.internalCache(client);
if (responseCache == null) return;

// Should we cache this response for this request?
if (!CacheStrategy.isCacheable(userResponse, networkRequest)) {
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
responseCache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
return;
}

// Offer this request to the cache.
//这里将响应头信息缓存到缓存文件中,对应缓存文件“****.0”
storeRequest = responseCache.put(stripBody(userResponse));
}

/**

  • Returns a new source that writes bytes to {@code cacheRequest} as they are read by the source
  • consumer. This is careful to discard bytes left over when the stream is closed; otherwise we
  • may never exhaust the source stream and therefore not complete the cached response.
    */
    //缓存响应体信息
    private Response cacheWritingResponse(final CacheRequest cacheRequest, Response response)
    throws IOException {
    // Some apps return a null body; for compatibility we treat that like a null cache request.
    if (cacheRequest == null) return response;
    Sink cacheBodyUnbuffered = cacheRequest.body();
    if (cacheBodyUnbuffered == null) return response;

final BufferedSource source = response.body().source();
final BufferedSink cacheBody = Okio.buffer(cacheBodyUnbuffered);

Source cacheWritingSource = new Source() {
boolean cacheRequestClosed;

//这里就是从响应体体读取数据,保存到缓存文件中,对应缓存文件“****.1”
@Override public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead;
try {
bytesRead = source.read(sink, byteCount);
} catch (IOException e) {
if (!cacheRequestClosed) {
cacheRequestClosed = true;
cacheRequest.abort(); // Failed to write a complete cache response.
}
throw e;
}

if (bytesRead == -1) {
if (!cacheRequestClosed) {
cacheRequestClosed = true;
cacheBody.close(); // The cache response is complete!
}
return -1;
}

sink.copyTo(cacheBody.buffer(), sink.size() - bytesRead, bytesRead);
cacheBody.emitCompleteSegments();
return bytesRead;
}

@Override public Timeout timeout() {
return source.timeout();
}

@Override public void close() throws IOException {
if (!cacheRequestClosed
&& !discard(this, HttpStream.DISCARD_STREAM_TIMEOUT_MILLIS, MILLISECONDS)) {
cacheRequestClosed = true;
cacheRequest.abort();
}
source.close();
}
};

return response.newBuilder()
.body(new RealResponseBody(response.headers(), Okio.buffer(cacheWritingSource)))
.build();
}
}

可以看到这里先通过maybeCache写入了响应头信息,再通过cacheWritingResponse写入了响应体信息。我们再进去看Cache的put方法实现。

private CacheRequest put(Response response) throws IOException {
String requestMethod = response.request().method();

// 响应的请求方法不支持缓存,只有GET方法支持缓存
if (HttpMethod.invalidatesCache(response.request().method())) {
try {
remove(response.request());
} catch (IOException ignored) {
// The cache cannot be written.
}
return null;
}
// 同样,请求只支持GET方法的缓存
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 (OkHeaders.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;
}
}

我们继续看Cache的writeTo方法,可以看到是写入一些响应头信息。

public void writeTo(DiskLruCache.Editor editor) throws IOException {
BufferedSink sink = Okio.buffer(editor.newSink(ENTRY_METADATA));

最后为了帮助大家深刻理解Android相关知识点的原理以及面试相关知识,这里放上相关的我搜集整理的24套腾讯、字节跳动、阿里、百度2020-2021面试真题解析,我把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包知识脉络 + 诸多细节

还有 高级架构技术进阶脑图、Android开发面试专题资料 帮助大家学习提升进阶,也节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。

一线互联网面试专题

379页的Android进阶知识大全

379页的Android进阶知识大全

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

间来学习,也可以分享给身边好友一起学习。

[外链图片转存中…(img-kDO02AYh-1714511372701)]

[外链图片转存中…(img-Jz7KFPRY-1714511372701)]

[外链图片转存中…(img-Qn9SeY6C-1714511372702)]

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 23
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值