美文网首页
OkHttp源码学习之四 CallServerIntercept

OkHttp源码学习之四 CallServerIntercept

作者: leilifengxingmw | 来源:发表于2018-09-04 21:18 被阅读8次

    CallServerInterceptor 请求服务拦截器 整个责任链中最后一个拦截器,负责向服务器发送网络请求。

    Response getResponseWithInterceptorChain() throws IOException {
        // 构建一整套拦截器
        List<Interceptor> interceptors = new ArrayList<>();
        interceptors.addAll(client.interceptors());//1
        interceptors.add(retryAndFollowUpInterceptor);//2
        interceptors.add(new BridgeInterceptor(client.cookieJar()));//3
        interceptors.add(new CacheInterceptor(client.internalCache()));//4
        interceptors.add(new ConnectInterceptor(client));//5
        //构建一个RealCall的时候我们传入的forWebSocket是false
        if (!forWebSocket) {
          interceptors.addAll(client.networkInterceptors());//6
        }
        interceptors.add(new CallServerInterceptor(forWebSocket));//7
        //构建拦截器链
        Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, 
    null, 0,originalRequest, this, eventListener, client.connectTimeoutMillis(),
            client.readTimeoutMillis(), client.writeTimeoutMillis());
        //拦截器链处理请求
        return chain.proceed(originalRequest);
      }
    

    在CacheInterceptor之后是ConnectInterceptor, 负责建立一个到目标服务器的连接,然后把请求交给下一个拦截器处理。暂且略过。ConnectInterceptor 就是今天的主题CallServerInterceptor了。

    CallServerInterceptor的intercept方法

     @Override public Response intercept(Chain chain) throws IOException {
        RealInterceptorChain realChain = (RealInterceptorChain) chain;
        HttpCodec httpCodec = realChain.httpStream();
        StreamAllocation streamAllocation = realChain.streamAllocation();
        RealConnection connection = (RealConnection) realChain.connection();
        Request request = realChain.request();
    
        long sentRequestMillis = System.currentTimeMillis();
    
        realChain.eventListener().requestHeadersStart(realChain.call());
       //1. 发送请求头
        httpCodec.writeRequestHeaders(request);
        realChain.eventListener().requestHeadersEnd(realChain.call(), request);
    
        Response.Builder responseBuilder = null;
         //2. 如果请求方法可以发送请求体,而且请求体不为null
        if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
          //2.1 如果请求的头部有"Expect: 100-continue"的信息,那么我们在发送请求体之前,要等待一个 "HTTP/1.1 100
          //Continue" 的响应。如果我们没有获取这个 "HTTP/1.1 100 Continue"响应,就返回我们获取的响应(例如4xx响应)并不再发送请求体。
          if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
            httpCodec.flushRequest();
            realChain.eventListener().responseHeadersStart(realChain.call());
            //4. 解析响应头信息,如果有 100的响应码的话,返回null
            responseBuilder = httpCodec.readResponseHeaders(true);
          }
          //2.2 responseBuilder == null
          if (responseBuilder == null) {
            // Write the request body if the "Expect: 100-continue" expectation was met.
            realChain.eventListener().requestBodyStart(realChain.call());
            long contentLength = request.body().contentLength();
            CountingSink requestBodyOut =
                new CountingSink(httpCodec.createRequestBody(request, contentLength));
            BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
            //发送请求体
            request.body().writeTo(bufferedRequestBody);
            bufferedRequestBody.close();
            realChain.eventListener()
                .requestBodyEnd(realChain.call(), requestBodyOut.successfulCount);
          } else if (!connection.isMultiplexed()) {
            //如果我们请求头部有"Expect: 100-continue"的信息,但是服务器并没有返回100,那么禁止HTTP/1的连接被使用。
           //否则,我们仍然有义务传输请求正文以使连接保持一致状态。
            streamAllocation.noNewStreams();
          }
        }
        //结束请求
        httpCodec.finishRequest();
    
        if (responseBuilder == null) {
          realChain.eventListener().responseHeadersStart(realChain.call());
          //5. 构建响应头
          responseBuilder = httpCodec.readResponseHeaders(false);
        }
        //6. 构建初始响应
        Response response = responseBuilder
            .request(request)
            .handshake(streamAllocation.connection().handshake())
            .sentRequestAtMillis(sentRequestMillis)
            .receivedResponseAtMillis(System.currentTimeMillis())
            .build();
    
        int code = response.code();
        if (code == 100) {
          // 7. 如果我们没有强求服务端发送100的响应码,但是服务端却发送了一个100的响应码,那么我们就尝试重新获取真正的响应
          responseBuilder = httpCodec.readResponseHeaders(false);
          
          response = responseBuilder
                  .request(request)
                  .handshake(streamAllocation.connection().handshake())
                  .sentRequestAtMillis(sentRequestMillis)
                  .receivedResponseAtMillis(System.currentTimeMillis())
                  .build();
          //重新获取响应码
          code = response.code();
        }
    
        realChain.eventListener()
                .responseHeadersEnd(realChain.call(), response);
    
        //我们传入的forWebSocket是false,不会走这个判断
        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 {
          //8. 构建响应体
          response = response.newBuilder()
              .body(httpCodec.openResponseBody(response))
              .build();
        }
        //9. 关闭连接
        if ("close".equalsIgnoreCase(response.request().header("Connection"))
            || "close".equalsIgnoreCase(response.header("Connection"))) {
          streamAllocation.noNewStreams();
        }
        //10. 如果响应码为204,或者205,但是响应体长度大于0,抛出异常
        if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
          throw new ProtocolException(
              "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
        }
        //11. 返回响应
        return response;
      }
    
    1. 先发送请求头
    httpCodec.writeRequestHeaders(request);
    
    1. 如果请求方法可以发送请求体,而且请求体不为null,在这种情况下,我们可以发送请求体。

      2.1 如果请求的头部有"Expect: 100-continue"的信息,那么我们在发送请求体之前,要等待一个 "HTTP/1.1 100
      //Continue" 的响应。如果我们没有获取这个 "HTTP/1.1 100 Continue"响应,就返回我们获取的响应(例如4xx响应)并不再发送请求体。

          if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
            httpCodec.flushRequest();
            realChain.eventListener().responseHeadersStart(realChain.call());
            //4. 解析响应头信息
            responseBuilder = httpCodec.readResponseHeaders(true);
          }
        
    
    1. 解析响应头信息,如果有 100的响应码的话,返回null。 HttpCodec的readResponseHeaders方法
     /**
       * 解析HTTP响应头
       *
       * @param expectContinue 如果传入的参数expectContinue为true的话,那么如果响应的响应码是100的话,这个方法返回null。
       *                       否则此方法永远不会返回null。
       */
      Response.Builder readResponseHeaders(boolean expectContinue) throws IOException;
    
    

    2.2 responseBuilder == null.分两种情况。1 是我们的请求头中并没有Expect: 100-continue的信息;2 是请求头中有Expect: 100-continue的信息,服务器返回了响应100。这两种情况,都需要继续发送请求体。

          if (responseBuilder == null) {
            // Write the request body if the "Expect: 100-continue" expectation was met.
            realChain.eventListener().requestBodyStart(realChain.call());
            long contentLength = request.body().contentLength();
            CountingSink requestBodyOut =
                new CountingSink(httpCodec.createRequestBody(request, contentLength));
            BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
            //发送请求体
            request.body().writeTo(bufferedRequestBody);
            bufferedRequestBody.close();
            realChain.eventListener()
                .requestBodyEnd(realChain.call(), requestBodyOut.successfulCount);
          } 
    

    请求体发送完以后,就结束请求。结束请求后的后续步骤。

    1. 先构建响应头
    2. 然后构建初始响应。
    3. 此时,如果我们没有强求服务端发送100的响应码,但是服务端却发送了一个100的响应码,那么我们就尝试重新获取真正的响应。
    4. 构建响应体。
    5. 构建响应体之后关闭连接。
    6. 如果响应码为204,或者205,但是响应体长度大于0,抛出异常
    7. 最终返回响应。

    最终的响应还要一级级向上传递。
    ConnectInterceptor->ConnectInterceptor->CacheInterceptor->BridgeInterceptor->RetryAndFollowUpInterceptor

    总结:到此,OkHttp的源码学习暂时告一段落,后续会不断更新完善。

    参考链接

    1. okhttp源码分析(五)-CallServerInterceptor过滤器

    相关文章

      网友评论

          本文标题:OkHttp源码学习之四 CallServerIntercept

          本文链接:https://www.haomeiwen.com/subject/mjpnwftx.html