Okhttp你应该懂的源码,其实并不难

2019-11-28  本文已影响0人  kwbsky

看这篇文章前,可以先阅读一下我的另外一篇简单介绍http的文章,有助于更好的理解本文。文章链接:https://www.jianshu.com/p/6da88b1efdaf

val request = Request.Builder()
            .method("POST", FormBody.Builder().add("userId","232423432").build())
            .header("token","asfwaefaslfd")
            .url("http://www.test.com/user/getUserInfo")
            .build()
    val response = OkHttpClient().newCall(request).execute()
    val jsonString = response.body()?.string()

这是我用post做了表单提交,请求头加入了token。首先看一下我们代码中提供的信息是否符合http协议需要的元素。回顾一下介绍http的那篇文章,一个完整的请求包括了什么?URL:http://www.test.com/user/getUserInfo, 请求方法:POST,uri:/user/getUserInfo, http版本号:这个一般是固定的,框架会给我们写好默认值,请求头:token,由于是post的表单提交,请求体中的内容:
userId=232423432。
好了,该有的都有了,就可以发起http请求了。
我们需要明确一点,okhttp到底是干什么的?我们必须知道一个前提,网络通信抽象到编程,其实就是socket编程。所以okhttp就是对socket编程的封装,以更简便更友好的调用方式,供各位开发者使用。那么在看源码前,我们可以大胆猜测,okhttp的工作就是把以上所有的信息做一个整合,然后传递给socket,接下来的事情就不用我们操心了,socket负责搞定一切。当然了,还有响应部分,也是由socket返回的,一般我们使用的都是响应体里的json字符串,那么从二进制流转化为字符串也是okhttp替我们做的工作。都说得这么具体了,您脑子里总该有个大体的认识了吧。如果还没有,那么,请转行吧。

开始分析源码了!
首先是request的构造,很熟悉对不对,builder#build。

Request(Builder builder) {
    this.url = builder.url;
    this.method = builder.method;
    this.headers = builder.headers.build();
    this.body = builder.body;
    this.tag = builder.tag != null ? builder.tag : this;
  }

一般这种结构,我们只需要看构造函数即可。很显然就是把builder获取到的信息都赋值给request。我们一个一个看。url的类型是HttpUrl,看下源码:

public static @Nullable HttpUrl parse(String url) {
    Builder builder = new Builder();
    Builder.ParseResult result = builder.parse(null, url);
    return result == Builder.ParseResult.SUCCESS ? builder.build() : null;
  }

通过这个方法构造了一个httpurl对象,那么这个对象到底干嘛的呢,我们来看下他的全局变量就明白了。

/** Either "http" or "https". */
  final String scheme;

  /** Decoded username. */
  private final String username;

  /** Decoded password. */
  private final String password;

  /** Canonical hostname. */
  final String host;

  /** Either 80, 443 or a user-specified port. In range [1..65535]. */
  final int port;

soga,我们传入的参数是一个url,这个类把他分解成了主机名(即域名),端口号,并且通过url来判断是http还是https。
继续看,method是个字符串,也就是我们传入的方法POST。
Headers类看名字就是存请求头的,那么里面应该有个map,进去看一下。

public final class Headers {
  private final String[] namesAndValues;
}

很遗憾不是,是一个字符串数组。他存的方式是一个key,一个value,比如数组的第一个是key,第二个value,第三个key,第四个value,总之数组长度是双数的。我们通过存储的代码来验证一下。

public Builder header(String name, String value) {
      headers.set(name, value);
      return this;
    }
public Builder set(String name, String value) {
      checkNameAndValue(name, value);
      removeAll(name);
      addLenient(name, value);
      return this;
    }
Builder addLenient(String name, String value) {
      namesAndValues.add(name);
      namesAndValues.add(value.trim());
      return this;
    }
final List<String> namesAndValues = new ArrayList<>(20);

键值对存到了Headers的内部类Builder的List中,就是我们上面说这种存储方式。再来看下怎么传给Headers的,因为是builder#build通过构造函数传递的,我们来看下:

Headers(Builder builder) {
    this.namesAndValues = builder.namesAndValues.toArray(new String[builder.namesAndValues.size()]);
  }

就是把刚才的list转成了数组赋值给了headers的存键值对的数组。
继续说body,他的类型是RequestBody,他是干嘛的呢?我们知道,socket编程,数据从应用层流向tcp层,必须要转成二进制流才能被接收。所以他的作用就是把我们的请求体内容转成二进制流。我们以最常用的字符串转流为例来看一下:

public static RequestBody create(@Nullable MediaType contentType, String content) {
    Charset charset = Util.UTF_8;
    if (contentType != null) {
      charset = contentType.charset();
      if (charset == null) {
        charset = Util.UTF_8;
        contentType = MediaType.parse(contentType + "; charset=utf-8");
      }
    }
    byte[] bytes = content.getBytes(charset);
    return create(contentType, bytes);
  }
public static RequestBody create(final @Nullable MediaType contentType, final byte[] content) {
    return create(contentType, content, 0, content.length);
  }
public static RequestBody create(final @Nullable MediaType contentType, final byte[] content,
      final int offset, final int byteCount) {
    if (content == null) throw new NullPointerException("content == null");
    Util.checkOffsetAndCount(content.length, offset, byteCount);
    return new RequestBody() {
      @Override public @Nullable MediaType contentType() {
        return contentType;
      }

      @Override public long contentLength() {
        return byteCount;
      }

      @Override public void writeTo(BufferedSink sink) throws IOException {
        sink.write(content, offset, byteCount);
      }
    };
  }

关注writeTo方法,这里就是最终写入了流。有同学会问,sink是什么。这个是okio的东西,是square公司自己封装的一套有关流的代码。有兴趣的同学可以自行看一下源码,他其实就是对java输入输出流的封装。
request就分析完了,他拥有了我们http需要的数据,之后会用到。

val response = OkHttpClient().newCall(request).execute()

@Override public Call newCall(Request request) {
    return RealCall.newRealCall(this, request, false /* for web socket */);
  }

static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    // Safely publish the Call instance to the EventListener.
    RealCall call = new RealCall(client, originalRequest, forWebSocket);
    call.eventListener = client.eventListenerFactory().create(call);
    return call;
  }

newCall是个静态方法,就是创建了一个call的实现类realcall,把request传给他,然后调用execute方法:

@Override public Response execute() throws IOException {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    try {
      client.dispatcher().executed(this);
      Response result = getResponseWithInterceptorChain();
      if (result == null) throw new IOException("Canceled");
      return result;
    } catch (IOException e) {
      eventListener.callFailed(this, e);
      throw e;
    } finally {
      client.dispatcher().finished(this);
    }
  }

先来看client.dispatcher().executed(this);这句

synchronized void executed(RealCall call) {
    runningSyncCalls.add(call);
  }

private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();

Dispatcher类是个分发类,主要作用就是借他的手来分发需要执行的任务。既然控制分发的,肯定需要做记录。runningSyncCalls 就是记录正在执行的call对应的网络请求。有记录必定有删除,对的,我们看下execute方法里的finally实现,无论网络请求过程是否有异常,最终必须把当前这个call从记录队列里删除。

private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
    int runningCallsCount;
    Runnable idleCallback;
    synchronized (this) {
      if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
      if (promoteCalls) promoteCalls();
      runningCallsCount = runningCallsCount();
      idleCallback = this.idleCallback;
    }

    if (runningCallsCount == 0 && idleCallback != null) {
      idleCallback.run();
    }
  }

再看下一行:

Response result = getResponseWithInterceptorChain();

我靠,这一个方法就直接返回response了,这也太简单了吧。
大兄弟,别这么天真行吗?

Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    interceptors.add(retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));

    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

    return chain.proceed(originalRequest);
  }

前面的都只是铺垫,这个方法里的实现才是正戏。
这里使用了非严格的职责连模式,把网络请求需要的步骤分别封装进了几个拦截器里,然后用一个叫RealInterceptorChain的东西串了起来。是不是很巧妙,复杂的结构瞬间清晰了不少。题外话,这个模式我们在view的点击事件分发里看到过,这个模式的好处就是使复杂的结构简化。
谨慎起见,这里还是分析一下这条链到底是怎么串起来的。
首先是把若干拦截器添加到一个叫interceptors的list里,然后把他传入chain的构造函数创建chain,最后调用chain的proceed方法。进入chain看一下:

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {
    calls++;
    ...
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);
    ...

    return response;
  }

核心代码就3句,我们一句句分析。
又new了一个chain出来,然后把之前的interceptors又传了进去,第5个参数index+1,这个index是一个全局变量,初始值是0,那么这里传入的就是1。
接下来获取了interceptors的第0个拦截器,调用了他的intercept方法,并把刚才new出来的chain传了进去。那么intercept方法又做了什么呢?这是一个抽象方法,返回值是Response。我们随便打开一个拦截器看下,都可以发现,这个返回的response是通过chain#proceed返回的。那么这时候调用栈又进去了proceed方法。这时候的index已经是1了(刚才new的时候传入的),然后又new了一个chain,第5个参数传的index+1就变成2了,取出第2个拦截器,调用他的intercept方法,并且把index为2的chain传了进去。到这里这条链就开始启动了,源源不断的传下去。有细心的同学就会问了,那何时是个头呢?代码里也没有判断到了最后一个就return啊。我们来看下最后一个拦截器CallServerInterceptor,你会发现这里面并没有再调用chain#proceed,所以自然而然这条链就停下来了。那又有同学问了,会不会最后一个拦截器不是CallServerInterceptor呢?大兄弟,这个顺序是写死的,不会变的。说到这里顺便提一句,我们平常自己也会写一些拦截器去动态的对请求数据做一些处理,这些拦截器是放在链条的最头上的,也就是client.interceptors()。如果把他放到CallServerInterceptor后面去,那就嗝儿屁了,人家通信都完成了,你还搞个毛啊。
接下来就来分析下几个拦截器分别做了什么。

拦截器之RetryAndFollowUpInterceptor

顾名思义就是处理重试和重定向的。

@Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Call call = realChain.call();
    EventListener eventListener = realChain.eventListener();

    StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
        createAddress(request.url()), call, eventListener, callStackTrace);
    this.streamAllocation = streamAllocation;

    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      if (canceled) {
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response;
      boolean releaseConnection = true;
      try {
        response = realChain.proceed(request, streamAllocation, null, null);
        releaseConnection = false;
      } catch (RouteException e) {
        // The attempt to connect via a route failed. The request will not have been sent.
        if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {
          throw e.getLastConnectException();
        }
        releaseConnection = false;
        continue;
      } catch (IOException e) {
        // An attempt to communicate with a server failed. The request may have been sent.
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;
        releaseConnection = false;
        continue;
      } finally {
        // We're throwing an unchecked exception. Release any resources.
        if (releaseConnection) {
          streamAllocation.streamFailed(null);
          streamAllocation.release();
        }
      }

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

      Request followUp = followUpRequest(response, streamAllocation.route());

      if (followUp == null) {
        if (!forWebSocket) {
          streamAllocation.release();
        }
        return response;
      }

      closeQuietly(response.body());

      if (++followUpCount > MAX_FOLLOW_UPS) {
        streamAllocation.release();
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }

      if (followUp.body() instanceof UnrepeatableRequestBody) {
        streamAllocation.release();
        throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
      }

      if (!sameConnection(response, followUp.url())) {
        streamAllocation.release();
        streamAllocation = new StreamAllocation(client.connectionPool(),
            createAddress(followUp.url()), call, eventListener, callStackTrace);
        this.streamAllocation = streamAllocation;
      } else if (streamAllocation.codec() != null) {
        throw new IllegalStateException("Closing the body of " + response
            + " didn't close its backing stream. Bad interceptor?");
      }

      request = followUp;
      priorResponse = response;
    }
  }

在一个死循环里面,调用chain#proceed获取response。如果是第一次,那么priorResponse为空。然后通过followUpRequest方法获取一个新的request,如果没有获取到,那么直接返回了之前的response。那么核心代码就是这个followUpRequest:

private Request followUpRequest(Response userResponse, Route route) throws IOException {
    if (userResponse == null) throw new IllegalStateException();
    int responseCode = userResponse.code();

    final String method = userResponse.request().method();
    switch (responseCode) {
      case HTTP_PROXY_AUTH:
        Proxy selectedProxy = route != null
            ? route.proxy()
            : client.proxy();
        if (selectedProxy.type() != Proxy.Type.HTTP) {
          throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
        }
        return client.proxyAuthenticator().authenticate(route, userResponse);

      case HTTP_UNAUTHORIZED:
        return client.authenticator().authenticate(route, userResponse);

      case HTTP_PERM_REDIRECT:
      case HTTP_TEMP_REDIRECT:
        // "If the 307 or 308 status code is received in response to a request other than GET
        // or HEAD, the user agent MUST NOT automatically redirect the request"
        if (!method.equals("GET") && !method.equals("HEAD")) {
          return null;
        }
        // fall-through
      case HTTP_MULT_CHOICE:
      case HTTP_MOVED_PERM:
      case HTTP_MOVED_TEMP:
      case HTTP_SEE_OTHER:
        // Does the client allow redirects?
        if (!client.followRedirects()) return null;

        String location = userResponse.header("Location");
        if (location == null) return null;
        HttpUrl url = userResponse.request().url().resolve(location);

        // Don't follow redirects to unsupported protocols.
        if (url == null) return null;

        // If configured, don't follow redirects between SSL and non-SSL.
        boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
        if (!sameScheme && !client.followSslRedirects()) return null;

        // Most redirects don't include a request body.
        Request.Builder requestBuilder = userResponse.request().newBuilder();
        if (HttpMethod.permitsRequestBody(method)) {
          final boolean maintainBody = HttpMethod.redirectsWithBody(method);
          if (HttpMethod.redirectsToGet(method)) {
            requestBuilder.method("GET", null);
          } else {
            RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
            requestBuilder.method(method, requestBody);
          }
          if (!maintainBody) {
            requestBuilder.removeHeader("Transfer-Encoding");
            requestBuilder.removeHeader("Content-Length");
            requestBuilder.removeHeader("Content-Type");
          }
        }

        // When redirecting across hosts, drop all authentication headers. This
        // is potentially annoying to the application layer since they have no
        // way to retain them.
        if (!sameConnection(userResponse, url)) {
          requestBuilder.removeHeader("Authorization");
        }

        return requestBuilder.url(url).build();

      case HTTP_CLIENT_TIMEOUT:
        // 408's are rare in practice, but some servers like HAProxy use this response code. The
        // spec says that we may repeat the request without modifications. Modern browsers also
        // repeat the request (even non-idempotent ones.)
        if (!client.retryOnConnectionFailure()) {
          // The application layer has directed us not to retry the request.
          return null;
        }

        if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
          return null;
        }

        if (userResponse.priorResponse() != null
            && userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {
          // We attempted to retry and got another timeout. Give up.
          return null;
        }

        if (retryAfter(userResponse, 0) > 0) {
          return null;
        }

        return userResponse.request();

      case HTTP_UNAVAILABLE:
        if (userResponse.priorResponse() != null
            && userResponse.priorResponse().code() == HTTP_UNAVAILABLE) {
          // We attempted to retry and got another timeout. Give up.
          return null;
        }

        if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) {
          // specifically received an instruction to retry without delay
          return userResponse.request();
        }

        return null;

      default:
        return null;
    }
  }

主要就是根据response的状态码来对号入座,构造新的requst并返回,如果一个也没对应上,就返回null,说明不需要重试或者重定向。这里举个例子,比如HTTP_SEE_OTHER,303,代表重定向。那么这里就从response的头里取Location字段,这个值代表重定向的url,如果能拿到就用他重新去构建一个request。如果request为null,那么直接返回response并且跳出死循环。

拦截器之BridgeInterceptor
@Override public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();

    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");
        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;
      requestBuilder.header("Accept-Encoding", "gzip");
    }

    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());
    }

    Response networkResponse = chain.proceed(requestBuilder.build());

    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

    Response.Builder responseBuilder = networkResponse.newBuilder()
        .request(userRequest);

    if (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);
      String contentType = networkResponse.header("Content-Type");
      responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
    }

    return responseBuilder.build();
  }

仔细看一下,其实就是往请求头里加键值对。如果对这些头字段不了解的最好去搜索一下。这些都是okhttp已经帮我构建好的,如果没有框架要我们自己写的话,这些头字段都是要自己实现的。
因为比较简单,这里就不一一解释了,大家自行查看。

拦截器之ConnectInterceptor
@Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    StreamAllocation streamAllocation = realChain.streamAllocation();

    // We need the network to satisfy this request. Possibly for validating a conditional GET.
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();

    return realChain.proceed(request, streamAllocation, httpCodec, connection);
  }

我们看来streamAllocation#newStream:

public HttpCodec newStream(
      OkHttpClient client, Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
    try {
      RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
          writeTimeout, pingIntervalMillis, connectionRetryEnabled, doExtensiveHealthChecks);
      HttpCodec resultCodec = resultConnection.newCodec(client, chain, this);

      synchronized (connectionPool) {
        codec = resultCodec;
        return resultCodec;
      }
    } catch (IOException e) {
      throw new RouteException(e);
    }
  }

private RealConnection findHealthyConnection(int connectTimeout, int readTimeout,
      int writeTimeout, int pingIntervalMillis, boolean connectionRetryEnabled,
      boolean doExtensiveHealthChecks) throws IOException {
    while (true) {
      RealConnection candidate = findConnection(connectTimeout, readTimeout, writeTimeout,
          pingIntervalMillis, connectionRetryEnabled);
  ...
  }

private RealConnection findConnection(int connectTimeout, int readTimeout, int writeTimeout,
      int pingIntervalMillis, boolean connectionRetryEnabled) throws IOException {
        ...
        result.connect(connectTimeout, readTimeout, writeTimeout, pingIntervalMillis,
        connectionRetryEnabled, call, eventListener);
    routeDatabase().connected(result.route());
        ...
}

代码有点长,只保留了核心的部分。其实就是去找一个叫RealConnection的东西。那怎么找呢?okhttp做了一个缓存池叫ConnectionPool,里面存放了RealConnection的队列。取的时候就是循环队列,如果address所对应的主机名一样,那么就命中。拿到RealConnection以后调用他的connect方法。

public void connect(int connectTimeout, int readTimeout, int writeTimeout,
      int pingIntervalMillis, boolean connectionRetryEnabled, Call call,
      EventListener eventListener) {
        if (route.requiresTunnel()) {
          connectTunnel(connectTimeout, readTimeout, writeTimeout, call, eventListener);
          if (rawSocket == null) {
            // We were unable to connect the tunnel but properly closed down our resources.
            break;
          }
        } else {
          connectSocket(connectTimeout, readTimeout, call, eventListener);
        }
        establishProtocol(connectionSpecSelector, pingIntervalMillis, call, eventListener);
        eventListener.connectEnd(call, route.socketAddress(), route.proxy(), protocol);
        break;
}

private void connectSocket(int connectTimeout, int readTimeout, Call call,
      EventListener eventListener) throws IOException {
    Proxy proxy = route.proxy();
    Address address = route.address();

    rawSocket = proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.HTTP
        ? address.socketFactory().createSocket()
        : new Socket(proxy);

    eventListener.connectStart(call, route.socketAddress(), proxy);
    rawSocket.setSoTimeout(readTimeout);
    try {
      Platform.get().connectSocket(rawSocket, route.socketAddress(), connectTimeout);
    } catch (ConnectException e) {
      ConnectException ce = new ConnectException("Failed to connect to " + route.socketAddress());
      ce.initCause(e);
      throw ce;
    }
try {
      source = Okio.buffer(Okio.source(rawSocket));
      sink = Okio.buffer(Okio.sink(rawSocket));
    } catch (NullPointerException npe) {
      if (NPE_THROW_WITH_NULL.equals(npe.getMessage())) {
        throw new IOException(npe);
      }
    }

创建了socket,并且调用了connect方法。至此socket就开始进行3次握手了,此方法是阻塞的。如果成功了,再创建source和sink。我们之前分析过,source和sink是okhttp自己写的输入输出流,其实是对java的输入输出流的封装。我们来看下是不是这样的:
Okio#source

public static Source source(Socket socket) throws IOException {
    if (socket == null) throw new IllegalArgumentException("socket == null");
    if (socket.getInputStream() == null) throw new IOException("socket's input stream == null");
    AsyncTimeout timeout = timeout(socket);
    Source source = source(socket.getInputStream(), timeout);
    return timeout.source(source);
  }

拿到了socket的输入流去构建source。sink也是一样的道理。
至此,socket连接工作已经完成,接下来就是输出请求信息了。

拦截器之CallServerInterceptor
httpCodec.writeRequestHeaders(request);

@Override public void writeRequestHeaders(Request request) throws IOException {
    String requestLine = RequestLine.get(
        request, streamAllocation.connection().route().proxy().type());
    writeRequest(request.headers(), requestLine);
  }

RequestLine#get

public static String get(Request request, Proxy.Type proxyType) {
    StringBuilder result = new StringBuilder();
    result.append(request.method());
    result.append(' ');

    if (includeAuthorityInRequestLine(request, proxyType)) {
      result.append(request.url());
    } else {
      result.append(requestPath(request.url()));
    }

    result.append(" HTTP/1.1");
    return result.toString();
  }

是不是很熟悉,就是把请求行的3个元素拼成字符串,中间用空格隔开,然后最终是怎么写入流的呢?

public void writeRequest(Headers headers, String requestLine) throws IOException {
    if (state != STATE_IDLE) throw new IllegalStateException("state: " + state);
    sink.writeUtf8(requestLine).writeUtf8("\r\n");
    for (int i = 0, size = headers.size(); i < size; i++) {
      sink.writeUtf8(headers.name(i))
          .writeUtf8(": ")
          .writeUtf8(headers.value(i))
          .writeUtf8("\r\n");
    }
    sink.writeUtf8("\r\n");
    state = STATE_OPEN_REQUEST_BODY;
  }

看到了吗?严格按照我们之前讲的http,先把拼接好的请求行写入流,然后换行,然后循环写入headers的key和value,中间用冒号隔开,每写一对都要换行。最后再一个空的换行。

CountingSink requestBodyOut =
            new CountingSink(httpCodec.createRequestBody(request, contentLength));
        BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);

        request.body().writeTo(bufferedRequestBody);

调用requestbody的writeTo方法,requestbody是抽象类,我以表单提交formbody为例:

@Override public void writeTo(BufferedSink sink) throws IOException {
    writeOrCountBytes(sink, false);
  }

private long writeOrCountBytes(@Nullable BufferedSink sink, boolean countBytes) {
    long byteCount = 0L;

    Buffer buffer;
    if (countBytes) {
      buffer = new Buffer();
    } else {
      buffer = sink.buffer();
    }

    for (int i = 0, size = encodedNames.size(); i < size; i++) {
      if (i > 0) buffer.writeByte('&');
      buffer.writeUtf8(encodedNames.get(i));
      buffer.writeByte('=');
      buffer.writeUtf8(encodedValues.get(i));
    }

    if (countBytes) {
      byteCount = buffer.size();
      buffer.clear();
    }

    return byteCount;
  }

这里其实就是把表单的键值对写入sink,key=value,中间用&隔开。最后调用httpCodec#finishRequest就把请求信息都写入流了。
接着就是解析响应流了。

if (responseBuilder == null) {
      realChain.eventListener().responseHeadersStart(realChain.call());
      responseBuilder = httpCodec.readResponseHeaders(false);
    }

@Override public Response.Builder readResponseHeaders(boolean expectContinue) throws IOException {
    if (state != STATE_OPEN_REQUEST_BODY && state != STATE_READ_RESPONSE_HEADERS) {
      throw new IllegalStateException("state: " + state);
    }

    try {
      StatusLine statusLine = StatusLine.parse(readHeaderLine());

      Response.Builder responseBuilder = new Response.Builder()
          .protocol(statusLine.protocol)
          .code(statusLine.code)
          .message(statusLine.message)
          .headers(readHeaders());

      if (expectContinue && statusLine.code == HTTP_CONTINUE) {
        return null;
      } else if (statusLine.code == HTTP_CONTINUE) {
        state = STATE_READ_RESPONSE_HEADERS;
        return responseBuilder;
      }

      state = STATE_OPEN_RESPONSE_BODY;
      return responseBuilder;
    } catch (EOFException e) {
      // Provide more context if the server ends the stream before sending a response.
      IOException exception = new IOException("unexpected end of stream on " + streamAllocation);
      exception.initCause(e);
      throw exception;
    }
  }

逻辑很简单,就是解析出状态行和响应头,根据状态行和响应头构建一个responseBuilder。那么我们来看一下状态行和响应头的解析过程。

private String readHeaderLine() throws IOException {
    String line = source.readUtf8LineStrict(headerLimit);
    headerLimit -= line.length();
    return line;
  }

public static StatusLine parse(String statusLine) throws IOException {
    // H T T P / 1 . 1   2 0 0   T e m p o r a r y   R e d i r e c t
    // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0

    // Parse protocol like "HTTP/1.1" followed by a space.
    int codeStart;
    Protocol protocol;
    if (statusLine.startsWith("HTTP/1.")) {
      if (statusLine.length() < 9 || statusLine.charAt(8) != ' ') {
        throw new ProtocolException("Unexpected status line: " + statusLine);
      }
      int httpMinorVersion = statusLine.charAt(7) - '0';
      codeStart = 9;
      if (httpMinorVersion == 0) {
        protocol = Protocol.HTTP_1_0;
      } else if (httpMinorVersion == 1) {
        protocol = Protocol.HTTP_1_1;
      } else {
        throw new ProtocolException("Unexpected status line: " + statusLine);
      }
    } else if (statusLine.startsWith("ICY ")) {
      // Shoutcast uses ICY instead of "HTTP/1.0".
      protocol = Protocol.HTTP_1_0;
      codeStart = 4;
    } else {
      throw new ProtocolException("Unexpected status line: " + statusLine);
    }

    // Parse response code like "200". Always 3 digits.
    if (statusLine.length() < codeStart + 3) {
      throw new ProtocolException("Unexpected status line: " + statusLine);
    }
    int code;
    try {
      code = Integer.parseInt(statusLine.substring(codeStart, codeStart + 3));
    } catch (NumberFormatException e) {
      throw new ProtocolException("Unexpected status line: " + statusLine);
    }

    // Parse an optional response message like "OK" or "Not Modified". If it
    // exists, it is separated from the response code by a space.
    String message = "";
    if (statusLine.length() > codeStart + 3) {
      if (statusLine.charAt(codeStart + 3) != ' ') {
        throw new ProtocolException("Unexpected status line: " + statusLine);
      }
      message = statusLine.substring(codeStart + 4);
    }

    return new StatusLine(protocol, code, message);
  }

实际上就是从流的最头上开始读取,直到第一个换行符,刚好就是第一个行响应行,然后把字符串进行解析。我们知道http的版本号是以HTTP/1.开头的,那么第8个字符和字符0做减运算,如果结果是0说明第8个字符是‘0’,如果是1说明第8个字符是‘1’,所以版本好分别是HTTP/1.0或者HTTP/1.1。第9个字符是空格,那么状态码就是从第10个字符开始,总共3个字符。

codeStart = 9;
code = Integer.parseInt(statusLine.substring(codeStart, codeStart + 3));

没错,代码中也是这么截取的。
最后判断,如果状态行的总长度大于到状态码为止的长度,那么就有响应短语。状态码后面是空格,所以从状态码最后一位+1开始截响应短语。
好了,再来分析响应头是怎么解析的。

public Headers readHeaders() throws IOException {
    Headers.Builder headers = new Headers.Builder();
    // parse the result headers until the first blank line
    for (String line; (line = readHeaderLine()).length() != 0; ) {
      Internal.instance.addLenient(headers, line);
    }
    return headers.build();
  }

readHeaderLine我们在取响应行的时候已经分析了,就是已换行符作为一次结束的标志,不停取出每一行。

@Override public void addLenient(Headers.Builder builder, String line) {
        builder.addLenient(line);
      }

Builder addLenient(String line) {
      int index = line.indexOf(":", 1);
      if (index != -1) {
        return addLenient(line.substring(0, index), line.substring(index + 1));
      } else if (line.startsWith(":")) {
        // Work around empty header names and header names that start with a
        // colon (created by old broken SPDY versions of the response cache).
        return addLenient("", line.substring(1)); // Empty header name.
      } else {
        return addLenient("", line); // No header name.
      }
    }

Builder addLenient(String name, String value) {
      namesAndValues.add(name);
      namesAndValues.add(value.trim());
      return this;
    }

逻辑很清晰,就是把每一行用冒号分割成key和value,然后添加到headers中。
到这里,就差一个最重要的responseBody了。

response = response.newBuilder()
          .body(httpCodec.openResponseBody(response))
          .build();

@Override public ResponseBody openResponseBody(Response response) throws IOException {
    streamAllocation.eventListener.responseBodyStart(streamAllocation.call);
    String contentType = response.header("Content-Type");

    if (!HttpHeaders.hasBody(response)) {
      Source source = newFixedLengthSource(0);
      return new RealResponseBody(contentType, 0, Okio.buffer(source));
    }

    if ("chunked".equalsIgnoreCase(response.header("Transfer-Encoding"))) {
      Source source = newChunkedSource(response.request().url());
      return new RealResponseBody(contentType, -1L, Okio.buffer(source));
    }

    long contentLength = HttpHeaders.contentLength(response);
    if (contentLength != -1) {
      Source source = newFixedLengthSource(contentLength);
      return new RealResponseBody(contentType, contentLength, Okio.buffer(source));
    }

    return new RealResponseBody(contentType, -1L, Okio.buffer(newUnknownLengthSource()));
  }

正常情况下是分片的,所以会创建RealResponseBody并返回,构造函数会传入最重要的source。以后我们调用responseBody#string将流转成字符串,这个流就是我们在构造函数传入的source。这里有关source和子类之间的关系有点绕,我怕说不清楚这里就不多解释了。有兴趣的同学可以自行去看一下,其实也就是不停套用装饰者模式。
ok,到这里我们的response就构建完成了。
接下里的事就给交给应用层的开发者了。

后面我将分析retrofit2.0的源码。

上一篇 下一篇

猜你喜欢

热点阅读