Retrofit Interceptor(拦截器) 拦截请求并做相关处理

本文详细介绍了Retrofit Interceptor的使用,包括如何通过拦截器修改请求header和添加统一参数。通过分析Interceptor接口和Chain对象,展示了如何在拦截器中处理Request和Response,并提供了一个包含插入公共参数和添加header功能的示例代码。文章指出,对于复杂的文件传输,需要额外注意。拦截器的使用相对简单,示例代码可供直接应用。
摘要由CSDN通过智能技术生成

本文介绍Retrofit拦截器(Interceptor)的使用方法及相关注意事项
首先看一下Interceptor源码:

/**
* Observes, modifies, and potentially short-circuits requests going out and the corresponding
* responses coming back in. Typically interceptors add, remove, or transform headers on the request
* or response.
*/

public interface Interceptor {
   
    Response intercept(Chain chain) throws IOException;

    interface Chain {
        Request request();

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

先看一下api描述,翻译过来其实就是可以通过拦截器拦截即将发出的请求及对响应结果做相应处理,典型的处理方式是修改header。其实我们可能不仅要处理header,有时也需要添加统一参数,都可以在拦截器内部完成。

看一下Interceptor接口,只有intercept(Chain chain)方法,其返回值是Response,顾名思义,是响应数据,我们要做的也就是重写该方法以达到我们的目的。intercept(Chain chain)方法中有个Chain参数,Chain是Interceptor接口内部中定义的另一个接口,我们暂且不管Retrofit内部是如何实现该接口的(这部分内容将会在新的文章中统一讲解),现在只需要知道调用其request()方法可以拿到Request,调用其proceed(Request request)方法可以得到相应数据即可。

到此为止,Interceptor基本用法已经知晓,下面上示例代码:

public class CommonInterceptor implements Interceptor {
   

    private static Map<String, String> commonParams;

    public synchronized static void setCommonParam(Map<String, String> commonParams) {
        if (commonParams != null) {
            if (CommonInterceptor.commonParams != null) {
                CommonInterceptor.commonParams.clear();
            } else {
                CommonInterceptor.commonParams = new HashMap<>();
            }
            for (String paramKey : commonParams.keySet()) {
                CommonInterceptor.commonParams.put(paramKey, commonParams.get(paramKey));
            }
        }
    }

    public synchronized static void updateOrInsertCommonParam(@NonNull String paramKey, @NonNull String paramValue) {
        if (commonParams == null) {
            commonParams = new HashMap<>();
        }
        commonParams.put(paramKey, paramValue);
    }

    @Override
    public synchronized Response intercept(Chain chain) throws IOException {
        Request request = rebuildRequest(chain.request());
        Response response = chain.proceed(request);
        // 输出返回结果
        try 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值