OkHttp(二) — Interceptor 拦截器

一、概述

OkHttp 版本: 3.14.7

OkHttp(一) — OkHttp 调用流程分析 中,我们介绍了一个请求的调用流程。请求最后是在 RealCall.getResponseWithInterceptorChain() 方法中执行的。

拦截器中 intercept() 方法的执行逻辑主要分为三部分:

  1. 在发起请求前对 request 进行处理。
  2. 调用下一个拦截器,获取 response。
  3. 对 Response 进行处理,并返回给上一个拦截器。

本篇文章我们来具体分析这几个拦截器的作用:

序号 拦截器 作用
1 interceptors 用户自定义拦截器,可以实现日志打印
2 RetryAndFollowUpInterceptor 负责失败重连以及重定向
3 BridgeInterceptor 负责请求和响应的转换
4 CacheInterceptor 负责处理缓存
5 ConnectInterceptor 负责与服务器构建连接
6 networkInterceptors 用户自定义网络拦截器,可以实现日志打印
7 CallServerInterceptor 负责数据传输

二、RetryAndFollowUpInterceptor

RetryAndFollowUpInterceptor 负责失败重连以及重定向。

//RetryAndFollowUpInterceptor.class

//最大重试次数:
private static final int MAX_FOLLOW_UPS = 20;
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Transmitter transmitter = realChain.transmitter();

    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      	// 这个执行连接前的准备工作。
      	transmitter.prepareToConnect(request);

      	if (transmitter.isCanceled()) {
        	throw new IOException("Canceled");
      	}

      Response response;
      boolean success = false;
      try {
        	//执行下一个拦截器,即BridgeInterceptor
        	response = realChain.proceed(request, transmitter, null);
        	success = true;
      } catch (RouteException e) {
        	// The attempt to connect via a route failed. The request will not have been sent.
        	//检测路由异常是否能重新连接
        	if (!recover(e.getLastConnectException(), transmitter, false, request)) {
          		throw e.getFirstConnectException();
        	}
        	continue; //重新进行while循环,进行网络请求
      } catch (IOException e) {
        	// An attempt to communicate with a server failed. The request may have been sent.
        	boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        	//检测该IO异常是否能重新连接
        	if (!recover(e, transmitter, requestSendStarted, request)) 
        		throw e;
        	continue; //重新进行while循环,进行网络请求
      } finally {
        	// The network call threw an exception. Release any resources.
        	if (!success) {// 由于上面抛出了异常,所以要释放相关资源。
          		transmitter.exchangeDoneDueToException();
        	}
      }

      // Attach the prior response if it exists. Such responses never have a body.
      if (priorResponse != null) {
        	response = response.newBuilder()
            	.priorResponse(priorResponse.newBuilder().body(null).build())
            	.build();
      }

      Exchange exchange = Internal.instance.exchange(response);
      Route route = exchange != null ? exchange.connection().route() : null;
      // 通过响应码判断当前的请求是否需要重定向,否则直接返回。
      Request followUp = followUpRequest(response, route);

      if (followUp == null) {
        	if (exchange != null && exchange.isDuplex()) {
          		transmitter.timeoutEarlyExit();
        	}
        	return response; //正常的情况下,这里就返回的响应报文response
      }

      RequestBody followUpBody = followUp.body();
      if (followUpBody != null && followUpBody.isOneShot()) {
        	return response;
      }

      closeQuietly(response.body());
      if (transmitter.hasExchange()) {
        	exchange.detachWithViolence();
      }

      if (++followUpCount > MAX_FOLLOW_UPS) { //重试次数不能大于限定的次数
        	throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }

      request = followUp;
      priorResponse = response;
    }
}

三、BridgeInterceptor

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.

BridgeInterceptor 是一个将用户态请求构建成真正网络请求,同时将网络返回数据构建成用户响应数据的桥梁。
这部分可以参考:OkHttp 官方文档 - Rewriting Requests部分

涉及到的几个请求头字段:

序号 请求头名称 含义
1 Content-Type 请求的与实体对应的MIME信息
2 Content-Length 请求的内容长度
3 Transfer-Encoding 文件传输编码 (如:chunked)
4 Host 指定请求的服务器的域名和端口号
5 Connection 表示是否需要持久连接 (如:Keep-Alive)
6 Accept-Encoding 接收者支持的类型 (如:gzip)
7 Cookie HTTP请求发送时,会把保存在该请求域名下的所有cookie值一起发送给web服务器
8 User-Agent User-Agent的内容包含发出请求的用户信息
//BridgeInterceptor.class
public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    // 将用户态的请求构建称网络请求
    Request.Builder requestBuilder = userRequest.newBuilder();

	// 1.下面就是将请求头需要的参数添加到请求头
    RequestBody body = userRequest.body();
    if (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"); //支持分片传输
        //由于支持分片传输,所以请求体的长度content-length没有意义,可以移除。
        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.
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
      transparentGzip = true; //1.1开启压缩
      requestBuilder.header("Accept-Encoding", "gzip"); //这里默认时支持gzip压缩的
    }

	//1.2 加载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());
    }

	// 2.这里实际上是调用下一个 Interceptor(即CacheInterceptor) 获取Response
    Response networkResponse = chain.proceed(requestBuilder.build());
	// 3.如果cookieJar不为空,则将响应报文的请求头保存到cookie中。
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

	// 根据之前的响应报文新构建一个Response
    Response.Builder responseBuilder = networkResponse.newBuilder()
        .request(userRequest);

	// 4.如果上面开启了数据压缩,这里要解压。
    if (transparentGzip
        && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
        && HttpHeaders.hasBody(networkResponse)) {
      // 返回的Response报文,body数据是压缩过的,所以需要使用Gzip解压缩。
      GzipSource responseBody = new GzipSource(networkResponse.body().source());
      // 同时移除响应头部的Content-Encoding,Content-Length
      Headers strippedHeaders = networkResponse.headers().newBuilder()
          .removeAll("Content-Encoding")
          .removeAll("Content-Length")
          .build();
      responseBuilder.headers(strippedHeaders);
      String contentType = networkResponse.header("Content-Type");
      // 将解压后的body重新放入Response中。
      responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
    }
	// 5.返回Response
    return responseBuilder.build();
}

小结:

  1. 在发送请求阶段,BridgeInterceptor 补充了网络请求需要的请求头(header)信息:Content-TypeContent-LengthTransfer-EncodingHostConnectionAccept-EncodingUser-Agent

    1.1 Accept-Encoding 是否开启gzip压缩。
    1.2 加载 Cookie。

  2. 创建真正的 request 并传递给后续的 interceptor(CacheInterceptor) 来处理,并等待获取响应。
  3. 获取到响应后,先保存Cookie。
  4. 如果服务器返回的响应content是以gzip压缩过的,则会先进行解压缩,并移除响应报文header的 Content-EncodingContent-Length,构造新的响应返回。
  5. 返回response。

四、CacheInterceptor

CacheInterceptor 类是专门处理缓存的,缓存相关的类有:

  1. Cache
  2. CacheStrategy
  3. DiskLruCache
  4. CacheInterceptor
  5. CacheControl

此处我们暂时先分析涉及的缓存拦截器(CacheInterceptor)。

//CacheInterceptor.class
public Response intercept(Chain chain) throws IOException {
	//1.如果存在缓存,则从缓存中取出,有可能为null
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

    long now = System.currentTimeMillis();
	// 2.获取缓存策略对象
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    // 策略中的网络请求
    Request networkRequest = strategy.networkRequest;
    // 策略中的缓存响应
    Response cacheResponse = strategy.cacheResponse;

    if (cache != null) {
      cache.trackResponse(strategy);
    }
    if (cacheCandidate != null && cacheResponse == null) {
      closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
    }

    // If we're forbidden from using the network and the cache is insufficient, fail.
    // 3.禁止使用网络(根据缓存策略),且缓存又无效,直接返回异常(504)的响应报文。
    if (networkRequest == null && cacheResponse == null) {
      return new Response.Builder()
          .request(chain.request())
          .protocol(Protocol.HTTP_1_1)
          .code(504)
          .message("Unsatisfiable Request (only-if-cached)")
          .body(Util.EMPTY_RESPONSE)
          .sentRequestAtMillis(-1L)
          .receivedResponseAtMillis(System.currentTimeMillis())
          .build();
    }

    // If we don't need the network, we're done.
    // 4.上面判断了缓存跟网络请求都为null的场景,因此这里网络请求为空时,缓存一定存在且缓存有效,所以直接返回缓存数据。
    if (networkRequest == null) {
      // 直接返回缓存(走缓存策略,其实到这一步就结束了,然后返回到上一级拦截器BridgeInterceptor)
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }

    Response networkResponse = null;
    try {
      // 5.执行到这里,说明缓存没有命中,需要执行网络请求。
      networkResponse = chain.proceed(networkRequest);
    } finally {
      // If we're crashing on I/O or otherwise, don't leak the cache body.
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }

    // If we have a cache response too, then we're doing a conditional get.
    // 执行到这里说明 networkRequest 跟 cacheResponse 都不为null。
    if (cacheResponse != null) {
      // 6. HTTP_NOT_MODIFIED=304 说明内容无变化,还是从缓存获取数据,并将网络报文返回的请求头更新到缓存的请求头中。
      if (networkResponse.code() == HTTP_NOT_MODIFIED) { 
        Response response = cacheResponse.newBuilder()
            .headers(combine(cacheResponse.headers(), networkResponse.headers()))
            .sentRequestAtMillis(networkResponse.sentRequestAtMillis())
            .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
            .cacheResponse(stripBody(cacheResponse))
            .networkResponse(stripBody(networkResponse))
            .build();
        networkResponse.body().close();

        // Update the cache after combining headers but before stripping the
        // Content-Encoding header (as performed by initContentStream()).
        cache.trackConditionalCacheHit();
        // 更新缓存
        cache.update(cacheResponse, response);
        return response;
      } else {//走到这里,说明服务端数据有变化。
        closeQuietly(cacheResponse.body());
      }
    }
	//7.使用网络响应
    Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

    if (cache != null) {
      //8.缓存到本地
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        // Offer this request to the cache.
        // 注意:Cache.put()操作只支持Get操作。
        CacheRequest cacheRequest = cache.put(response);
        return cacheWritingResponse(cacheRequest, response);
      }

      if (HttpMethod.invalidatesCache(networkRequest.method())) {
        try {
          cache.remove(networkRequest);
        } catch (IOException ignored) {
          // The cache cannot be written.
        }
      }
    }
    return response;
}

小结:
CacheInterceptor 的操作流程如下:

  1. 如果配置缓存,则从缓存中取一次,缓存不一定存在。
  2. 根据获取到的缓存跟当前的请求来创建一个缓存策略。
  3. 如果当前请求禁止使用网络(根据缓存策略),且缓存无效,直接返回异常(504)的响应报文。
  4. 如果缓存有效,则直接从缓存中获取数据。
  5. 如果缓存无效,且网络请求有效,则执行下一个拦截器(ConnectInterceptor)的操作。
  6. 缓存有效的条件下,执行步骤5获取响应报文,如果响应 code=HTTP_NOT_MODIFIED,说明服务端数据无改变,则直接使用本地缓存数据。
  7. 如果响应报文 code !=HTTP_NOT_MODIFIED,说明服务端数据有改变,直接使用网络返回的报文。
  8. 更新本地的缓存。

注意:

  1. 目前 CacheInterceptor 缓存只支持 Get 请求 (可以查看 Cache.put() 源码)。

五、ConnectInterceptor

ConnectInterceptor 的主要作用是负责与服务器构建连接。

// ConnectInterceptor.class
public Response intercept(Chain chain) throws IOException {
  	RealInterceptorChain realChain = (RealInterceptorChain) chain;
  	Request request = realChain.request();
  	Transmitter transmitter = realChain.transmitter();

  	// We need the network to satisfy this request. Possibly for validating a conditional GET.
  	boolean doExtensiveHealthChecks = !request.method().equals("GET");
  	// 这一步很重要,构建一个Exchange对象,该对象传输单个HTTP请求和响应对。
  	Exchange exchange = transmitter.newExchange(chain, doExtensiveHealthChecks);

  	return realChain.proceed(request, transmitter, exchange);
}

下面看以下 transmitter.newExchange() 方法具体做了什么?

Transmitter

  1. 通过 ExchangeFinder 查找到一个处理网络请求编解码的类ExchangeCodec;
  2. 将 ExchangeCodec 传递给 Exchange 对象统一管理。
// Transmitter.class
Exchange newExchange(Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
	// ...代码省略...
  	// 通过ExchangeFinder构建一个ExchangeCodec,ExchangeCodec是一个网络请求编解码的类
   	ExchangeCodec codec = exchangeFinder.find(client, chain, doExtensiveHealthChecks);
   	// 将ExchangeCodec委托给Exchange统一管理。
   	Exchange result = new Exchange(this, call, eventListener, exchangeFinder, codec);

   	synchronized (connectionPool) {
     	this.exchange = result;
     	this.exchangeRequestDone = false;
     	this.exchangeResponseDone = false;
     	return result;
   	}
}

ExchangeFinder

//ExchangeFinder.class
public ExchangeCodec find(OkHttpClient client, Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
	int connectTimeout = chain.connectTimeoutMillis();
	int readTimeout = chain.readTimeoutMillis();
	int writeTimeout = chain.writeTimeoutMillis();
	int pingIntervalMillis = client.pingIntervalMillis();
	boolean connectionRetryEnabled = client.retryOnConnectionFailure();
	
	try {
		// 查找一个可以使用的连接通道。
	  	RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
	      writeTimeout, pingIntervalMillis, connectionRetryEnabled, doExtensiveHealthChecks);
	    // 通过RealConnection构造一个ExchangeCodec对象,处理请求和响应报文。
	  	return resultConnection.newCodec(client, chain);
	} catch (RouteException e) {
	  	trackFailure();
	  	throw e;
	} catch (IOException e) {
	  	trackFailure();
	  	throw new RouteException(e);
	}
}

/**
 * Finds a connection and returns it if it is healthy. If it is unhealthy the process is repeated
 * until a healthy connection is found.
 */
private RealConnection findHealthyConnection(int connectTimeout, int readTimeout,
    	int writeTimeout, int pingIntervalMillis, boolean connectionRetryEnabled,
    	boolean doExtensiveHealthChecks) throws IOException {
  	while (true) { //一直查找,直到找到可用的Connection。
  		// 从ConnectionPool中查找一个连接(RealConnection)
    	RealConnection candidate = findConnection(connectTimeout, readTimeout, writeTimeout,
        		pingIntervalMillis, connectionRetryEnabled);

		// 下面的条件校验,是为了判断上一步获取的连接是否正常可用,如果不可用,就继续查找查找。
    	// If this is a brand new connection, we can skip the extensive health checks.
    	synchronized (connectionPool) {
      		if (candidate.successCount == 0 && !candidate.isMultiplexed()) {
        		return candidate;
      		}
    	}

    	// Do a (potentially slow) check to confirm that the pooled connection is still good. If it
    	// isn't, take it out of the pool and start again.
    	if (!candidate.isHealthy(doExtensiveHealthChecks)) {
      		candidate.noNewExchanges();
      		continue;
    	}
    	return candidate;
  	}
}


private RealConnection findConnection(int connectTimeout, int readTimeout, int writeTimeout,
      int pingIntervalMillis, boolean connectionRetryEnabled) throws IOException {
	boolean foundPooledConnection = false;
	RealConnection result = null;
	Route selectedRoute = null;
	RealConnection releasedConnection;
	Socket toClose;
	synchronized (connectionPool) {
	  	if (transmitter.isCanceled()) throw new IOException("Canceled");
	  	hasStreamFailure = false; // This is a fresh attempt.
	
	  	// Attempt to use an already-allocated connection. We need to be careful here because our
	  	// already-allocated connection may have been restricted from creating new exchanges.
	  	releasedConnection = transmitter.connection;
	  	toClose = transmitter.connection != null && transmitter.connection.noNewExchanges
	      	? transmitter.releaseConnectionNoEvents()
	      	: null;
	
	  	if (transmitter.connection != null) {
	    	// We had an already-allocated connection and it's good.
	    	result = transmitter.connection;
	    	releasedConnection = null;
	  	}
	
	  	if (result == null) {
	    	// Attempt to get a connection from the pool.
	    	// 查找可以复用的连接
	   		if (connectionPool.transmitterAcquirePooledConnection(address, transmitter, null, false)) {
	      		foundPooledConnection = true;
	      		result = transmitter.connection; //这里表示找到了可以复用的连接
	    	} else if (nextRouteToTry != null) {
	      		selectedRoute = nextRouteToTry;
	      		nextRouteToTry = null;
	    	} else if (retryCurrentRoute()) {
	      		selectedRoute = transmitter.connection.route();
	    	}
	  	}
	}
	closeQuietly(toClose);
	
	if (releasedConnection != null) {
	  	eventListener.connectionReleased(call, releasedConnection);
	}
	if (foundPooledConnection) {
	  	eventListener.connectionAcquired(call, result);
	}
	if (result != null) {
	  	// If we found an already-allocated or pooled connection, we're done.
	  	//如果有已知连接且可用,则直接返回
	  	return result;
	}
	
	// If we need a route selection, make one. This is a blocking operation.
	boolean newRouteSelection = false;
	if (selectedRoute == null && (routeSelection == null || !routeSelection.hasNext())) {
	  	newRouteSelection = true;
	  	// 切换路由选择器
	 	routeSelection = routeSelector.next();
	}
	
	List<Route> routes = null;
	synchronized (connectionPool) {
	  	if (transmitter.isCanceled()) throw new IOException("Canceled");
	  	
		//在新的路由选择器里尝试获取连接。
	  	if (newRouteSelection) {
	    	// Now that we have a set of IP addresses, make another attempt at getting a connection from
	    	// the pool. This could match due to connection coalescing.
	    	routes = routeSelection.getAll();
	    	// 这里跟上面获取的方法一样,获取到连接就返赋值给result 
	    	if (connectionPool.transmitterAcquirePooledConnection(address, transmitter, routes, false)) {
	      		foundPooledConnection = true;
	      		result = transmitter.connection;
	    	}
	  	}
	
		//如果上一步该是没有获取到,则切换下一个路由选择器,并重新创建一个RealConnection。
	  	if (!foundPooledConnection) {
	    	if (selectedRoute == null) {
	      		selectedRoute = routeSelection.next();
	    	}
	
	    	// Create a connection and assign it to this allocation immediately. This makes it possible
	    	// for an asynchronous cancel() to interrupt the handshake we're about to do.
	    	// 如果上面的条件都不满足,则创建一个RealConnection
	    	result = new RealConnection(connectionPool, selectedRoute);
	    	connectingConnection = result;
	  	}
	}
	
	// If we found a pooled connection on the 2nd time around, we're done.
	if (foundPooledConnection) {
	  	eventListener.connectionAcquired(call, result);
	  	return result;
	}
	
	// Do TCP + TLS handshakes. This is a blocking operation.
	// 开始TCP的三次握手
	result.connect(connectTimeout, readTimeout, writeTimeout, pingIntervalMillis,
		    connectionRetryEnabled, call, eventListener);
	//计入数据库
	connectionPool.routeDatabase.connected(result.route());
	
	Socket socket = null;
	synchronized (connectionPool) {
	  	connectingConnection = null;
	  	// Last attempt at connection coalescing, which only occurs if we attempted multiple
	  	// concurrent connections to the same host.
	  	if (connectionPool.transmitterAcquirePooledConnection(address, transmitter, routes, true)) {
	    	// We lost the race! Close the connection we created and return the pooled connection.
	    	result.noNewExchanges = true;
	    	socket = result.socket();
	    	result = transmitter.connection;
	
	    	// It's possible for us to obtain a coalesced connection that is immediately unhealthy. In
	    	// that case we will retry the route we just successfully connected with.
	    	nextRouteToTry = selectedRoute;
	  	} else {
	  		//加入连接池
	    	connectionPool.put(result);
	    	transmitter.acquireConnectionNoEvents(result);
	  	}
	}
	closeQuietly(socket);
	
	eventListener.connectionAcquired(call, result);
	return result; //返回可用的连接
}

六、CallServerInterceptor

ConnectInterceptor 中已经成功连接到服务器,所以 CallServerInterceptor 的主要目的就是发送请求和回写响应报文。

public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    // 数据交换器
    Exchange exchange = realChain.exchange();
    Request request = realChain.request();

    long sentRequestMillis = System.currentTimeMillis();
	//1.写入请求头
    exchange.writeRequestHeaders(request);

    boolean responseHeadersStarted = false;
    Response.Builder responseBuilder = null;
    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
      	// If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100
      	// Continue" response before transmitting the request body. If we don't get that, return
      	// what we did get (such as a 4xx response) without ever transmitting the request body.
      	if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
      		exchange.flushRequest();
      		responseHeadersStarted = true;
      		exchange.responseHeadersStart();
      		responseBuilder = exchange.readResponseHeaders(true);
      	}

	  	//2.写入请求体
      	if (responseBuilder == null) {
        	if (request.body().isDuplex()) {
          		// Prepare a duplex body so that the application can send a request body later.
          		exchange.flushRequest();
          		BufferedSink bufferedRequestBody = Okio.buffer(exchange.createRequestBody(request, true));
          		request.body().writeTo(bufferedRequestBody); //将请求体写入服务器
        	} else {
          		// 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();
        	}
      	} else {
        	exchange.noRequestBody();
        	if (!exchange.connection().isMultiplexed()) {
          		// If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection
          		// from being reused. Otherwise we're still obligated to transmit the request body to
          		// leave the connection in a consistent state.
          		exchange.noNewExchangesOnConnection();
        	}
      	}
    } else {
      	exchange.noRequestBody();
    }
	// 这里完成了请求的写入
    if (request.body() == null || !request.body().isDuplex()) {
      	exchange.finishRequest();
    }

    if (!responseHeadersStarted) {
      	exchange.responseHeadersStart();
    }

	//3.读取报文的响应头
    if (responseBuilder == null) {
      	responseBuilder = exchange.readResponseHeaders(false);
    }

	// 这里构建响应报文的Response对象,此时只有响应头,还没有响应体。
    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;
}

小结: CallServerInterceptor 主要完成了4个操作:

  1. 写入请求头
  2. 写入请求体
  3. 读取响应头
  4. 读取响应体

发布了158 篇原创文章 · 获赞 26 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/Love667767/article/details/105015916