源码系列--OkHttp(CallServerInterceptor)

Posted anni-qianqian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了源码系列--OkHttp(CallServerInterceptor)相关的知识,希望对你有一定的参考价值。

Github下载源码地址https://github.com/square/okhttp

我们今天来看看拦截器里的CallServerInterceptor

来看CallServerInterceptor类的intercept方法

1)源码:

Exchange exchange = realChain.exchange();
Request request = realChain.request();

RealInterceptorChain类分别返回Exchange和Request对象

2)源码

exchange.writeRequestHeaders(request)

进到Exchange类

public void writeRequestHeaders(Request request) throws IOException {
  try {
    eventListener.requestHeadersStart(call);
    codec.writeRequestHeaders(request);
    eventListener.requestHeadersEnd(call, request);
  } catch (IOException e) {
    eventListener.requestFailed(call, e);
    trackFailure(e);
    throw e;
  }
}

进到ExchangeCodec的实现类Http1ExchangeCodec(Http1.1版本)的writeRequestHeaders方法

@Override public void writeRequestHeaders(Request request) throws IOException {
  String requestLine = RequestLine.get(
      request, realConnection.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();
}

这里是一些字符串的拼接和请求的判断

紧接着是Http1ExchangeCodec的writeRequest方法

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

可以看到是通过Okio的BufferedSink实现的

Exchange类的writeRequestHeaders方法的catch中的trackFailure会走失败流程,输出ErrorCode

3)源码

responseBuilder = exchange.readResponseHeaders(true);

进到Exchange类的readResponseHeaders方法,然后再进到Http1ExchangeCodec类的readResponseHeaders方法

看名字都知道是读响应头信息,进到StatusLine的parse方法里

4)源码

BufferedSink bufferedRequestBody = Okio.buffer(
    exchange.createRequestBody(request, true));

最终进到Http1ExchangeCodec类的createRequestBody方法中

5)CallServerInterceptor类的intercept方法最后是生成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();
}

总的来说,还是比较简单的,150行左右的代码。先写请求头,然后发送请求,最后得到响应

而且有两个类Http1ExchangeCodec和Http2ExchangeCodec,很好的适配了不同的http版本

欢迎关注我的微信公众号:安卓圈

技术图片

以上是关于源码系列--OkHttp(CallServerInterceptor)的主要内容,如果未能解决你的问题,请参考以下文章

源码系列-OkHttp

Android 10大开源常用框架源码解析 系列 网络框架之一 OkHttp杂题

《OkHttp源码分析》之 OkHttp的缓存管理

OkHttpOkHttp 源码分析 ( OkHttpClient.Builder 构造器源码分析 )

OkHttpOkHttp 源码分析 ( 网络框架封装 | OkHttp 4 迁移 | OkHttp 建造者模式 )

OkHttp源码解析(小白必看,建议收藏)