OkHttp3源码分支之拦截器CallServerInterceptor

tech2026-01-11  9

本文基于okhttp-3.14.9版本

本篇文章分析的就是这个CallServerInterceptor这个拦截器,此拦截器是链条上的最后一个拦截器,它对服务器进行网络调用

** This is the last interceptor in the chain. It makes a network call to the server. */ public final class CallServerInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { exchange.writeRequestHeaders(request); if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) { // Write the request body if the "Expect: 100-continue" expectation was met. BufferedSink bufferedRequestBody = Okio.buffer( exchange.createRequestBody(request, false)); request.body().writeTo(bufferedRequestBody); bufferedRequestBody.close(); } if (request.body() == null || !request.body().isDuplex()) { exchange.finishRequest(); } if (responseBuilder == null) { responseBuilder = exchange.readResponseHeaders(false); } Response response = responseBuilder .request(request) .handshake(exchange.connection().handshake()) .sentRequestAtMillis(sentRequestMillis) .receivedResponseAtMillis(System.currentTimeMillis()) .build(); int code = response.code(); if (code == 100) { // server sent a 100-continue even though we did not request one. // try again to read the actual response response = exchange.readResponseHeaders(false) .request(request) .handshake(exchange.connection().handshake()) .sentRequestAtMillis(sentRequestMillis) .receivedResponseAtMillis(System.currentTimeMillis()) .build(); code = response.code(); } exchange.responseHeadersEnd(response); if (forWebSocket && code == 101) { // Connection is upgrading, but we need to ensure interceptors see a non-null response body. response = response.newBuilder() .body(Util.EMPTY_RESPONSE) .build(); } else { response = response.newBuilder() .body(exchange.openResponseBody(response)) .build(); } if ("close".equalsIgnoreCase(response.request().header("Connection")) || "close".equalsIgnoreCase(response.header("Connection"))) { exchange.noNewExchangesOnConnection(); } if ((code == 204 || code == 205) && response.body().contentLength() > 0) { throw new ProtocolException( "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength()); } return response; } } 主要是通过Exchange操作请求,步骤有写入请求头、写入请求体、读取响应头、读取响应体最终由ExchangeCodec实现类Http1ExchangeCodec或者Http2ExchangeCodec负责编码解码处理exchange.writeRequestHeaders(request),写入请求体,通过Okio的bufferedSink其中exchange.finishRequest()完成请求,最终调用codec.finishRequest()完成请求,将请求刷新到底层套接字,并发出不再传输字节的信号exchange.readResponseHeaders(false),读取响应头,并构建一个响应Responseexchange.openResponseBody(response),读取响应体,并构建一个RealResponseBody最终返回Response
最新回复(0)