本篇文章继续深入源代码查看 BridgeInterceptor 拦截器相关的方法
BridgeInterceptor
查看 intercept 方法
@Override public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();// 取出 Request 实例
Request.Builder requestBuilder = userRequest.newBuilder();创建 Builder
RequestBody body = userRequest.body();// 取出body对象
if (body != null) {
MediaType contentType = body.contentType();
if (contentType != null) { //赋值 contentType 给 builder
requestBuilder.header("Content-Type", contentType.toString());
}
long contentLength = body.contentLength();
if (contentLength != -1) { // 赋值contentLength
requestBuilder.header("Content-Length", Long.toString(contentLength));
requestBuilder.removeHeader("Transfer-Encoding");
} else {
requestBuilder.header("Transfer-Encoding", "chunked");
requestBuilder.removeHeader("Content-Length");
}
}
if (userRequest.header("Host") == null) { // 赋值Host
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
}
if (userRequest.header("Connection") == null) { // 赋值Connection
requestBuilder.header("Connection", "Keep-Alive");
}
// If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
// the transfer stream.
boolean transparentGzip = false;
if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) { // 赋值 Accept-Encoding
transparentGzip = true;
requestBuilder.header("Accept-Encoding", "gzip");
}
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
if (!cookies.isEmpty()) {// 赋值 cookie
requestBuilder.header("Cookie", cookieHeader(cookies));
}
if (userRequest.header("User-Agent") == null) {// 赋值 User-Agent
requestBuilder.header("User-Agent", Version.userAgent());
}
Response networkResponse = chain.proceed(requestBuilder.build());// 调用下一个拦截器
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
if (transparentGzip
&& "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
&& HttpHeaders.hasBody(networkResponse)) { // 解析返回数据
GzipSource responseBody = new GzipSource(networkResponse.body().source());
Headers strippedHeaders = networkResponse.headers().newBuilder()
.removeAll("Content-Encoding")
.removeAll("Content-Length")
.build();
responseBuilder.headers(strippedHeaders);
String contentType = networkResponse.header("Content-Type");
responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
}
return responseBuilder.build();
}
可以看到 BridgeInterceptor 拦截器主要是取 Request 中的参数最后赋值给其内部类 requestBuilder ,requestBuilder 在之前构造 Request 已经对其进行实例化,此处即进行相关赋值;
总结 BridgeInterceptor 做了什么?
1、根据请求我们设置的参数,赋值 Request 相关数据到 Builder 中;
2、解析返回的数据;