OKHttp 拦截器使用技巧:仅对特定请求生效
可以考虑将拦截器加入到 OkHttpClient 实例中,然后将需要使用拦截器的请求通过拦截器的方式进行处理。具体实现如下:
- 创建一个 OkHttpClient 实例,并设置连接池以及拦截器:
OkHttpClient client = new OkHttpClient.Builder()
.connectionPool(new ConnectionPool()) // 设置连接池
.addInterceptor(new YourInterceptor()) // 添加拦截器
.build();
- 对于需要使用拦截器的请求,使用 Request.Builder 来创建请求,并设置拦截器:
Request request = new Request.Builder()
.url(url)
.addHeader('...') // 设置请求头
.method(method, body)
.tag(tag)
.build();
// 使用拦截器处理请求
Response response = client.newCall(request).execute();
- 对于不需要使用拦截器的请求,直接使用 OkHttpClient 来发送请求即可:
Request request = new Request.Builder()
.url(url)
.addHeader('...') // 设置请求头
.method(method, body)
.tag(tag)
.build();
// 不使用拦截器处理请求
Response response = client.newCall(request).execute();
这样可以实现对于特定请求使用拦截器的功能。
原文地址: https://www.cveoy.top/t/topic/owit 著作权归作者所有。请勿转载和采集!