Okhttp3拦截器-应用拦截器和网络拦截器的区别

Okhttp3拦截器-应用拦截器和网络拦截器的区别

96 lengyan_zhao 关注

2017.08.11 19:08* 字数 611 阅读 109评论 0喜欢 0

在Okhttp3中拦截器分为应用拦截器和网络拦截器,两者有很大的区别,在使用时一定要注意防止用错造成不必要的麻烦,接下来我将说明这两个拦截器的差异.

  • 首先看看Okhttp执行流程图

     

    拦截器执行过程

  • 再看拦截器执行顺序图

     

根据上面的两张图,我们可以列出Application Interceptor和Network Interceptor的执行流程图

流程图.png

Application interceptors

  • Don't need to worry about intermediate responses like redirects and retries.
    不需要关心是否重定向或者失败重连
  • Are always invoked once, even if the HTTP response is served from the cache.
    应用拦截器只会调用一次,即使数据来源于缓存
  • Observe the application's original intent. Unconcerned with OkHttp-injected headers like If-None-Match.
    只考虑应用的初始意图,不去考虑Okhhtp注入的Header比如:if-None-Match,意思就是不管其他外在因素只考虑最终的返回结果
  • Permitted to short-circuit and not call Chain.proceed().
    根据第二张图我们可以看出,自定义的应用拦截器是第一个开始执行的拦截器,所以这句话的意思就是,应用拦截器可以决定是否执行其他的拦截器,通过Chain.proceed().
  • Permitted to retry and make multiple calls to Chain.proceed().
    和上一句的意思差不多,可以执行多次调用其他拦截器,通过Chain.proceed().

Network Interceptors

  • Able to operate on intermediate responses like redirects and retries.
    根据第三张图,我们可以理解这句话的意思是,网络拦截器可以操作重定向和失败重连的返回值
  • Not invoked for cached responses that short-circuit the network.
    根据第一张图,我们可以以看出,这句换的意思是,取缓存中的数据就不会去还行Chain.proceed().所以就不能执行网络拦截器
  • Observe the data just as it will be transmitted over the network.
    意思是通过网络拦截器可以观察到所有通过网络传输的数据
  • Access to the Connection that carries the request.
    根据第二张图我们可以看出,请求服务连接的拦截器先于网络拦截器执行,所以在进行网络拦截器执行时,就可以看到Request中服务器请求连接信息,因为应用拦截器是获取不到对应的连接信息的。

猜你喜欢

转载自blog.csdn.net/xinzhou201/article/details/82154452