本文介绍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