series
OKio source code analysis
OKHttp source code parsing (1)—- overall process
OKHttp source code parsing (2) – RetryAndFollowUpInterceptor interceptor
(3)—- BridgeInterceptor
(4)—- CacheInterceptor
—- ConnectInterceptor
—- CallServerInterceptor
1. Introduction
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.
Bridging interceptors (content interceptors) convert user-constructed requests into requests sent to the server and responses returned by the server into user-friendly responses.
2. Source code analysis
@Override Public Response Intercept (Chain Chain) throws IOException {// Constructs a user-friendly request as a request request sent to the server userRequest = chain.request(); Request.Builder requestBuilder = userRequest.newBuilder(); RequestBody body = userRequest.body(); // If there is a request body, constructif(body ! = null) { MediaType contentType = body.contentType();if(contentType ! = null) { requestBuilder.header("Content-Type", contentType.toString());
}
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"); }}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 are 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"); } // Set cookie List< cookie > cookies = cookiejar.loadForRequest (userRequest.url());if(! cookies.isEmpty()) { requestBuilder.header("Cookie", cookieHeader(cookies));
}
if (userRequest.header("User-Agent") == null) {
requestBuilder.header("User-Agent", Version.userAgent()); } // Once constructed, pass the request to the next interceptor for processing. NetworkResponse networkResponse = chain.proceed(requestBuilder.build()); / / save networkResponse cookie HttpHeaders. ReceiveHeaders (cookieJar userRequest. Url (), networkResponse headers ()); / / will networkResponse structure for user-friendly response response. The Builder responseBuilder. = networkResponse newBuilder () .request(userRequest); // If networkResponse uses gzip and has a response body, set the response body to a user-friendly responseif (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);
responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
}
return responseBuilder.build();
}
Copy the code
BridgeInterceptor does two things: request header and response handling:
- Request header processing: Get the user’s request requestBuilder and complete the request header information in the request. Examples are content-type, Content-Length, Transfer-encoding, Host, Connection, Accept-encoding, Cookie, and User-agent
- Response: After receiving the response, place the requested request in the response, and set the body of the response to a user-friendly response if the response is gZIP encoded and has a body
Additional:
HTTP headers:
Header | explain | The sample |
---|---|---|
Accept | Specifies the type of content that the client can receive | Accept: text/plain, text/html,application/json |
Accept-Charset | A set of character encodings acceptable to the browser. | Accept-Charset: iso-8859-5 |
Accept-Encoding | Specifies the type of web server content compression encoding that the browser can support. | Accept-Encoding: compress, gzip |
Accept-Language | Browser acceptable language | Accept-Language: en,zh |
Accept-Ranges | You can request one or more subscope fields of a web page entity | Accept-Ranges: bytes |
Authorization | HTTP authorization certificate | Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
Cache-Control | Specify the caching mechanism that requests and responses follow | Cache-Control: no-cache |
Connection | Indicates whether a persistent connection is required. (HTTP 1.1 makes persistent connections by default) | Connection: close |
Cookie | When an HTTP request is sent, all cookie values stored under the domain name of the request are sent to the Web server. | Cookie: $Version=1; Skin=new; |
Content-Length | The content length of the request | Content-Length: 348 |
Content-Type | MIME information that corresponds to the entity being requested | Content-Type: application/x-www-form-urlencoded |
Date | The date and time the request was sent | Date: Tue, 15 Nov 2010 08:12:31 GMT |
Expect | The specific server behavior requested | Expect: 100-continue |
From | Email address of the user who made the request | From: [email protected] |
Host | Specifies the domain name and port number of the requested server | Host: www.zcmhi.com |
If-Match | This is valid only if the request content matches the entity | If – the Match: “737060 cd8c284d8af7ad3082f209582d” |
If-Modified-Since | If the part of the request is modified after the specified time, the request succeeds; if it is not modified, the 304 code is returned | If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT |
If-None-Match | If the content has not changed, the 304 code is returned with the Etag sent by the server. The Etag is compared with the Etag returned by the server to determine whether it has changed | If None – Match: “737060 cd8c284d8af7ad3082f209582d” |
If-Range | If the entity has not changed, the server sends the missing part of the client, otherwise sends the whole entity. The parameter is also Etag | If – Range: “737060 cd8c284d8af7ad3082f209582d” |
If-Unmodified-Since | The request succeeds only if the entity has not been modified after the specified time | If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT |
Max-Forwards | Limit the amount of time messages can be sent through proxies and gateways | Max-Forwards: 10 |
Pragma | Used to contain implementation-specific instructions | Pragma: no-cache |
Proxy-Authorization | Certificate of authorization to connect to the agent | Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== |
Range | Only a portion of the entity is requested, specifying scope | Range: bytes=500-999 |
Referer | The address of the previous web page, followed by the current requested web page, is the incoming path | Referer: www.zcmhi.com/archives. |
TE | The client is willing to accept the transmission code and notifies the server to accept the end plus header message | TE: trailers,deflate; Q = 0.5 |
Upgrade | Specify some transport protocol to the server for the server to convert (if supported) | Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/ X11 |
User-Agent | User-agent contains the information about the User that sends the request | The user-agent: Mozilla / 5.0 (Linux; X11) |
Via | Notification intermediate gateway or proxy server address, communication protocol | Via: Fred, 1.0 to 1.1nowhere.com(Apache / 1.1) |
Warning | Warning information about message entities | Warn: 199 Miscellaneous warning |
The Http response headers
Response headers | instructions | The sample | state |
---|---|---|---|
Access-Control-Allow-Origin | Specifies which web sites can be shared across domain source resources | Access-Control-Allow-Origin: * | temporary |
Accept-Patch | Specifies the document patch format supported by the server | Accept-Patch: text/example; charset=utf-8 | fixed |
Accept-Ranges | The range of content supported by the server | Accept-Ranges: bytes | fixed |
Age | The duration, in seconds, of the response object in the proxy cache | Age: 12 | fixed |
Allow | Valid actions for a particular resource; | Allow: GET, HEAD | fixed |
Cache-Control | Notify all caching mechanisms, from the server to the client, of whether or not they can cache the object and for how long. The unit is second | Cache-Control: max-age=3600 | fixed |
Connection | The options expected for the connection | Connection: close | fixed |
Content-Disposition | A description of a resource with a known MIME type. Based on the response header, the browser can decide whether to act on the returned resource, such as downloading or opening it. | Content-Disposition: attachment; filename=”fname.ext” | fixed |
Content-Encoding | The encoding type used to respond to the resource. Content-Encoding: gzip | fixed | |
Content-Language | Content-language: zh-cn | fixed | |
Content-Length | The Length of the response message body, expressed in base 8 bytes, content-Length: 348 | fixed | |
Content-Location | A candidate Location for the data returned is Content-location: /index.htm | fixed | |
Content-MD5 | The binary MD5 hash of the response content, encoded in Base64 | Content-md5: IDK0iSsgSW50ZWd0DiJUi== Deprecated | |
Content-Range | If it is a response part message, which part of the complete message | Content-range: bytes 21010-47021/47022 This parameter is fixed | |
Content-Type | The MIME type of the current content | Content-Type: text/html; charset=utf-8 | fixed |
Date | The date and time when this message was sent (in the “HTTP date “format defined in RFC 7231) | Date: Tue, 15 Nov 1994 08:12:31 GMT | fixed |
ETag | An identifier for a particular version of a resource, usually a message hash | ETag: “737060cd8c284d8af7ad3082f209582d” | fixed |
Expires | Specify a date/time after which this response is considered expired | Expires: Thu, 01 Dec 1994 16:00:00 GMT | Fixed: standard |
Last-Modified | The last modification date of the requested object (in the hypertext Transfer Protocol date format defined in RFC 7231) | Last-Modified: Dec, 26 Dec 2015 17:30:00 GMT | fixed |
Link | Represents a type relationship with another resource defined in RFC 5988 | Link: ; rel=”alternate” | fixed |
Location | Used when redirecting, or when a new resource is created. | Location: www.itbilu.com/nodejs | fixed |
P3P | P3P policy Settings | P3P: CP=”This is not a P3P policy! | fixed |
Pragma | Depending on the implementation, these response headers may have different effects at different times in the request/response chain | Pragma: no-cache | fixed |
Proxy-Authenticate | Requires authentication information when accessing the broker. | Proxy-Authenticate: Basic | fixed |
Public-Key-Pins | Used to prevent intermediate attacks and declare the certificate hash value of the transport layer security protocol in web site authentication | Public-Key-Pins: max-age=2592000; Pin – sha256 = “…” ; | fixed |
Refresh | Used for redirection, or when a new resource is created. The redirection will refresh after 5 seconds by default. | Refresh: 5; url=http://itbilu.com | |
Retry-After | If an entity is temporarily unavailable, this protocol header is used to tell the client to try again later. The value can be a specific time period (in seconds) or a hypertext Transfer Protocol date. | Example 1: retry-after: 120 Example 2: Retry-after: Dec, 26 Dec 2015 17:30:00 GMT | fixed |
Server | Server name | Server: nginx / 1.6.3 | fixed |
Set-Cookie | Set the HTTP cookies | Set-Cookie: UserID=itbilu; Max-Age=3600; Version=1 | Fixed: standard |
Status | The response header field of a generic gateway interface that describes the response status of the current HTTP connection. | Status: 200 OK | |
Trailer | Trailer user describes coding information for block coding in transit | Trailer: Max-Forwards | fixed |
Transfer-Encoding | A form of encoding transmitted to the user in the representation of an entity. Including chunked, COMPRESS, Deflate, gzip, and Identity. | Transfer-Encoding: chunked | fixed |
Upgrade | Requires the client to upgrade to another higher version protocol. | Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/ X11 | fixed |
vary | Inform the downstream proxy server how future request protocol headers should be matched to determine whether the cached response content can be used instead of re-requesting new content from the original server. | Vary: * | fixed |
Via | Tell the client of the proxy server by what route the current response is sent. | Via: Fred, 1.0 to 1.1itbilu.com(nginx / 1.6.3) | fixed |
Warning | General warning that there may be an error in the entity content body. | Warning: 199 Miscellaneous warning | fixed |
WWW-Authenticate | Represents the authentication mode that should be used when requesting this entity. | WWW-Authenticate: Basic | fixed |
References
HTTP request headers and request bodies
HTTP headers – Common HTTP request and response headers