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

在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中服务器请求连接信息,因为应用拦截器是获取不到对应的连接信息的。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容