首页 > 其他分享 >okhttp Interceptor

okhttp Interceptor

时间:2023-03-06 11:37:18浏览次数:44  
标签:拦截器 chain request interceptors okhttp Interceptor response

Interceptor介绍

okhttp的拦截器就是将整个请求网络的过程的每一步都封装在不同的Interceptor里,这样说可能有点绕,简单点说就是把一个List里的Interceptor都顺序执行一遍,那么整个网络请求过程就完成了

  @Throws(IOException::class)
  internal fun getResponseWithInterceptorChain(): Response {
    // Build a full stack of interceptors.
    val interceptors = mutableListOf<Interceptor>()
    interceptors += client.interceptors
    interceptors += RetryAndFollowUpInterceptor(client)
    interceptors += BridgeInterceptor(client.cookieJar)
    interceptors += CacheInterceptor(client.cache)
    interceptors += ConnectInterceptor
    if (!forWebSocket) {
      interceptors += client.networkInterceptors
    }
    interceptors += CallServerInterceptor(forWebSocket)

    val chain = RealInterceptorChain(
        call = this,
        interceptors = interceptors,
        index = 0,
        exchange = null,
        request = originalRequest,
        connectTimeoutMillis = client.connectTimeoutMillis,
        readTimeoutMillis = client.readTimeoutMillis,
        writeTimeoutMillis = client.writeTimeoutMillis
    )

    var calledNoMoreExchanges = false
    try {
      val response = chain.proceed(originalRequest)
      if (isCanceled()) {
        response.closeQuietly()
        throw IOException("Canceled")
      }
      return response
    } catch (e: IOException) {
      calledNoMoreExchanges = true
      throw noMoreExchanges(e) as Throwable
    } finally {
      if (!calledNoMoreExchanges) {
        noMoreExchanges(null)
      }
    }
  }

 

 

 

  • RetryAndFollowUpInterceptor:用于重定向和发生错误时重试
  • BridgeInterceptor:应用层与网络层的桥梁,从代码中看主要是为request添加请求头,为response去除响应头
  • CacheInterceptor:处理请求与响应缓存
  • ConnectInterceptor:与服务器建立连接
  • CallServerInterceptor:责任链中最后一个拦截器,用最终得到的request发送请求,将获取到response返回给前面的拦截器处理

这样application interceptornetwork interceptor的区别就很明显了,应用拦截器不会关注重定向和错误重试等操作,并且获取到的 requestresponse并不是网络层的。而网络拦截器则与之相反,如果发生了重定向和重试,那么会被调用多次,获取的requestresponse是完整的。

Application interceptors

  • 不用关注重定向、重试等中间响应
  • 只会调用一次
  • 只需关注应用发起请求的意图,不用关心okhttp为其添加的头部信息,比如 If-None-Match
  • 可以不调用Chain.proceed()不发送请求
  • 可以多次调用Chain.proceed()来重试请求

Network Interceptors

  • 可以操作重定向、重试等中间响应
  • 当返回缓存的响应时不会被调用
  • 可以获取到网络传输中真实的请求与响应
  • 可以访问带有请求的连接

Interceptor介绍

我们先看拦截器的接口定义:

public interface Interceptor {
    //拦截处理
    Response intercept(Chain chain) throws IOException;
    interface Chain {
        //获取请求的request
          Request request();
        //处理request获取response
        Response proceed(Request request) throws IOException;
    
        /**
         * Returns the connection the request will be executed on. This is only available in the chains
         * of network interceptors; for application interceptors this is always null.
         */
        @Nullable Connection connection();
    }
}

 

实例

比如我们现在有这样一个需求,为了保护用户远离甫田系,要将所有请求某竞价排名公司(baidu)的接口地址都直接替换成 www.soso.com

import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class KeepAwayBaiduInterceptor implements Interceptor {
    private static final String TAG = "KeepAwayBaiduInterceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Log.i(TAG, "intercept host: " + request.url().host());
        if (request.url().host().equals("www.baidu.com")) {
            //如果发现host属于该公司地址,就基于原来的request生成一个新的request,并使用新的url地址,这样之前request里的信息就都保留了
            Request newRequest = request.newBuilder().url("http://www.soso.com").build();
            return chain.proceed(newRequest);
        } else {
            return chain.proceed(request);
        }
    }
}

我们再看一下如何okhttp请求里使用这个自定义的Interceptor

  • okhttp发起请求代码
public void doRequest(){
    //创建okHttpClient对象
    OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new KeepAwayBaiduInterceptor())//在此处添加我们的拦截器
            .build();
    //创建一个该竞价排名公司的Request
    final Request request = new Request.Builder()
            .url("http://www.baidu.com")
            .build();

    Call call = mOkHttpClient.newCall(request);
    //请求加入调度
    call.enqueue(new Callback()
    {
        @Override
        public void onFailure(@NonNull Call call, @NonNull final IOException e) {
        }

        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException
        {
            final String htmlStr =  response.body().string();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView.setText("response:"+htmlStr);

                }
            });
        }
    });
}

总结

okhttp的拦截器就是在intercept(Chain chain)的回调中对Request和Response进行修改,然后通过chain.proceed(request)调起下一个拦截器。在okhttp中,网络连接也是一个拦截器(CallServerInterceptor),他是最后一个被调用的,负责将request写入网络流中,并从网络流中读取服务器返回的信息写入Response中返回给客户端

okhttpinterceptor采用的是责任链模式,在这条责任链中其中,前面的interceptor根据自己的需求处理request对象,处理完之后将其交给下一个interceptor,也就是上面代码中的chain.proceed(request)方法,然后等待下一个拦截器返回一个response,再对返回的结果进行处理,最终给请求的发起者返回一个响应结果。

标签:拦截器,chain,request,interceptors,okhttp,Interceptor,response
From: https://www.cnblogs.com/wanglongjiang/p/17183120.html

相关文章

  • struts2中MethodFilterInterceptor类的用法
    这个拦截器用于拦截部分函数。拦截器类packagecom.test.interceptor;importcom.opensymphony.xwork2.ActionInvocation;importcom.opensymphony.xwork2.interceptor.Meth......
  • 【Spring AOP】【十】Spring AOP源码解析-讲一下ExposeInvocationInterceptor
    1 前言不知道你在调试的时候,有没有发现我们的通知器链上首个元素会给我放进来一个ExposeInvocationInterceptor类型的通知器,看下图是不是,我们在之前其实也说过一次只是......
  • SpringMVC10 - 拦截器 Interceptor
    拦截器拦截器的配置SpringMVC中的拦截器用于拦截控制器方法的执行SpringMVC中的拦截器需要实现HandlerInterceptorSpringMVC的拦截器必须在SpringMVC的配置文件中进行......
  • 拦截器HandlerInterceptorAdapter使用方法
    原文链接:https://blog.csdn.net/kuishao1314aa/article/details/109777304一、Interceptor定义:拦截器是在面向切面编程中应用的,就是在你的service或者一个方法前调用一个......
  • okhttp之复习
    一okhttp 1.简介:官方简介:OkHttp是一个默认高效的HTTP客户端1、HTTP2支持允许对同一主机的所有请求共享一个套接字。2、透明GZIP缩小了下载大小。3、连接池减少了请求......
  • springmvc的Interceptor拦截器和servlet的filter过滤器
    springmvc的Interceptor拦截器和servlet的filter过滤器1、springmvc的Interceptor拦截器和servlet的filter过滤器springboot实现方式packagecom.liubaihui.lianxi01.co......
  • Okhttp 如何构建一个 Get 的 URL
    因项目的需要,构建一个微信请求的URL。URL的配置为:https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=......
  • OKHttpUtil搞定Http请求
    一、OKHttpUtil功能根据URL自动判断是请求HTTP还是HTTPS,不需要单独写多余的代码。默认情况下Cookie自动记录,比如可以实现模拟登录,即第一次访问登录URL后后续请求就是登......
  • Android 数据传递的几种方式,HttpLoggingInterceptor消息拦截器
    目录​​Android数据传递的几种方式​​​​一。用intent传递​​​​二。使用bundle进行传值:​​​​三。当antivity销毁时传递数据StartActivityForResult​​​​HttpLo......
  • SpringBoot之HandlerInterceptor拦截器的使用
    ​​1、SpringBoot之HandlerInterceptor拦截器的使用——(一)​​​​2、SpringBoot之HandlerInterceptor拦截器的使用——(二)自定义注解​​​​3、SpringBoot之HandlerInte......