Bridges from application code to network code. First it builds a network request from a user request. Then it proceeds to call the network. Finally it builds a user response from the network response.
publicfinalclassBridgeInterceptorimplementsInterceptor{privatefinalCookieJarcookieJar;publicBridgeInterceptor(CookieJarcookieJar){this.cookieJar=cookieJar;}@OverridepublicResponseintercept(Chainchain)throwsIOException{//------------------request处理
// 从「拦截器管理器」中拿到所谓的用户request
RequestuserRequest=chain.request();Request.BuilderrequestBuilder=userRequest.newBuilder();RequestBodybody=userRequest.body();// 各种桥接转换
if(body!=null){MediaTypecontentType=body.contentType();if(contentType!=null){requestBuilder.header("Content-Type",contentType.toString());}longcontentLength=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");}}if(userRequest.header("Host")==null){requestBuilder.header("Host",hostHeader(userRequest.url(),false));}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.
booleantransparentGzip=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));}// 附加OkHttp自己的UA
if(userRequest.header("User-Agent")==null){requestBuilder.header("User-Agent",Version.userAgent());}//------------------response处理
ResponsenetworkResponse=chain.proceed(requestBuilder.build());HttpHeaders.receiveHeaders(cookieJar,userRequest.url(),networkResponse.headers());Response.BuilderresponseBuilder=networkResponse.newBuilder().request(userRequest);if(transparentGzip&&"gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))&&HttpHeaders.hasBody(networkResponse)){GzipSourceresponseBody=newGzipSource(networkResponse.body().source());HeadersstrippedHeaders=networkResponse.headers().newBuilder().removeAll("Content-Encoding").removeAll("Content-Length").build();responseBuilder.headers(strippedHeaders);StringcontentType=networkResponse.header("Content-Type");responseBuilder.body(newRealResponseBody(contentType,-1L,Okio.buffer(responseBody)));}returnresponseBuilder.build();}/** Returns a 'Cookie' HTTP request header with all cookies, like {@code a=b; c=d}. */privateStringcookieHeader(List<Cookie>cookies){StringBuildercookieHeader=newStringBuilder();for(inti=0,size=cookies.size();i<size;i++){if(i>0){cookieHeader.append("; ");}Cookiecookie=cookies.get(i);cookieHeader.append(cookie.name()).append('=').append(cookie.value());}returncookieHeader.toString();}}