美文网首页
OKHttp的getResponseWithIntercepto

OKHttp的getResponseWithIntercepto

作者: 故江 | 来源:发表于2019-03-03 15:49 被阅读13次

同步请求中

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

同步请求中

@Override protected void execute() {
boolean signalledCallback =false;
timeout.enter();
try {
Response response = getResponseWithInterceptorChain();
if (retryAndFollowUpInterceptor.isCanceled()) {
signalledCallback =true;
responseCallback.onFailure(RealCall.this,new IOException("Canceled"));
}else {
signalledCallback =true;
responseCallback.onResponse(RealCall.this, response);
}
}catch (IOException e) {
e = timeoutExit(e);
if (signalledCallback) {
// Do not signal the callback twice!
        Platform.get().log(INFO,"Callback failure for " + toLoggableString(), e);
}else {
eventListener.callFailed(RealCall.this, e);
responseCallback.onFailure(RealCall.this, e);
}
}finally {
client.dispatcher().finished(this);
}
}
}

不管同步/异步请求都调用了同一个方法

Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();//拦截器的集合
    interceptors.addAll(client.interceptors());//向集合中添加创建OkHttpClient时外部添加的拦截器,用户自定义拦截器
    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));  //⑤         okHttp内部提供的五个拦截器

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

    return chain.proceed(originalRequest);
  }

getResponseWithInterceptorChain() 方法所做的就是构成了一个拦截的链,然后通过依次执行每一个不同功能的拦截器来获取服务器的响应返回。

getResponseWithInterceptorChain() 是怎么构成的链?

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

    //创建chain对象,也就是拦截器的链
    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

    return chain.proceed(originalRequest);//在完成拦截器的链的创建,得到调用它的proceed方法来执行请求
  }
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {
    if (index >= interceptors.size()) throw new AssertionError();

    calls++;

    // If we already have a stream, confirm that the incoming request will use it.
    if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must retain the same host and port");
    }

    // If we already have a stream, confirm that this is the only call to chain.proceed().
    if (this.httpCodec != null && calls > 1) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must call proceed() exactly once");
    }

    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);//index+1,表示如果我们下一次,访问,只能从下一个拦截器访问,而不能从当前拦截器访问
    Interceptor interceptor = interceptors.get(index);//得到index的当前拦截器
    Response response = interceptor.intercept(next);//通过得到拦截器在调用自身的intercept方法出入刚刚创建的拦截器链next,这样就把所有的拦截器链构成了一个完整的链条(每个拦截器都会执行这个方法)

    // Confirm that the next interceptor made its required call to chain.proceed().
    if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    }

    // Confirm that the intercepted response isn't null.
    if (response == null) {
      throw new NullPointerException("interceptor " + interceptor + " returned null");
    }

    if (response.body() == null) {
      throw new IllegalStateException(
          "interceptor " + interceptor + " returned a response with no body");
    }

    return response;//返回了响应信息。由于拦截器链RealInterceptorChain每次调用proceed()方法其实就是创建下一个拦截器链,这里的返回,其实是向上一个拦截器返回响应信息
  }

拦截器getResponseWithInterceptorChain()

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

1、用户自定义的拦截器
用在与服务器建立链接之前进行拦截

interceptors.addAll(client.interceptors());

2、RetryAndFollowUpInterceptor重试或失败重定向拦截器

 interceptors.add(retryAndFollowUpInterceptor);

3、BridgeInterceptor
校接和适配拦截器,主要补充用户创建请求当中的一些请求头Content-Type

interceptors.add(new BridgeInterceptor(client.cookieJar()));

4、CacheInterceptor主要处理缓存

interceptors.add(new CacheInterceptor(client.internalCache()));

5、ConnectInterceptor
与服务器创建链接,创建可以用的RealConnection(对java.io和java.nio进行了封装)

interceptors.add(new ConnectInterceptor(client));

6、用户自定义的拦截器
用在与服务器建立链接之后进行拦截。只有非socket进行设置

if (!forWebSocket) {
   interceptors.addAll(client.networkInterceptors());
}

7、CallServerInterceptor
向服务器发送请求和接收数据。将请求写入IO流,再从IO流中读取响应数据

interceptors.add(new CallServerInterceptor(forWebSocket));

8、RealInterceptorChain
主要就是将上述几个拦截器顺序执行。
从执行RetryAndFollowUpInterceptor->执行BridgeInterceptor->执行CacheInterceptor->执行ConnectInterceptor->执行CallServerInterceptor->依次将响应一一返回->返回到ConnectInterceptor->返回到CacheInterceptor->返回到BridgeInterceptor->返回到RetryAndFollowUpInterceptor。

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

相关文章

网友评论

      本文标题:OKHttp的getResponseWithIntercepto

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