BridgeInterceptor
该拦截器是链接客户端代码和网络代码的桥梁
- 将客户端构建的Request对象信息构建成真正的网络请求(设置请求头信息)
- 调用 RealInterceptorChain.proceed()进行网络请求,实际的结果就是会进入到下一个拦截器CacheInterceptor
- 将服务器返回的消息封装成一个Response对象
BridgeInterceptor部分源码
@Override
public Response intercept(Chain chain) throws IOException {
//获取用户构建的Request对象
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
RequestBody body = userRequest.body();
//设置Content-Type请求头
if (body != null) {
MediaType contentType = body.contentType();
if (contentType != null) {
requestBuilder.header("Content-Type", contentType.toString());
}
//Content-Length和Transfer-Encoding互斥
long contentLength = body.contentLength();
if (contentLength != -1) {
requestBuilder.header("Content-Length", Long.toString(contentLength));
requestBuilder.removeHeader("Transfer-Encoding");
} else {
requestBuilder.header("Transfer-Encoding", "chunked");
requestBuilder.removeHeader("Content-Length");
}
}
//设置Host请求头
if (userRequest.header("Host") == null) {
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
}
//设置Connection请求头
if (userRequest.header("Connection") == null) {
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) {
transparentGzip = true;
requestBuilder.header("Accept-Encoding", "gzip");
}
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
//设置Cookie请求头
if (!cookies.isEmpty()) {
requestBuilder.header("Cookie", cookieHeader(cookies));
}
//设置User-Agent请求头
if (userRequest.header("User-Agent") == null) {
requestBuilder.header("User-Agent", Version.userAgent());
}
//拦截器链继续往下运行
Response networkResponse = chain.proceed(requestBuilder.build());
//响应header, 如果没有自定义配置cookieJar==null,则什么都不做
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
//判断服务器是否支持gzip压缩格式,如果支持则交给kio压缩
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();
}
intercept()
的代码作用在注释中已经基本完成
- Request设置User-Agent、Cookie、Accept-Encoding等相关请求头信息
- 拦截器链继续往下运行,此时剩下拦截器工作就是返回真正的网络响应了(当然此响应可能是缓存的,也可能是服务器返回的最新数据)
- 将服务器返回的消息封装成一个Response对象