美文网首页
Retrofit2 — 参数拦截器

Retrofit2 — 参数拦截器

作者: 河婆墟邓紫棋 | 来源:发表于2016-08-15 00:27 被阅读615次

    使用retrofit2作为网络框架,可以用@Query注解来设置请求的查询参数,但如果部分请求或者全部请求都会带上一个同样的参数,依旧采用在每一个请求中设置参数的方案就显得笨重,本篇记录用拦截器设置多个请求的公共参数

    在OkHttpClient中添加拦截器,将请求拦截下来的请求得到HttpUrl,改写HttpUrl生成新的请求,然后手动执行新的带有公共参数的请求。

    import java.io.IOException;
    import okhttp3.Headers;
    import okhttp3.HttpUrl;
    import okhttp3.Interceptor;
    import okhttp3.Request;
    import okhttp3.Response;
    
    public class AddParamInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
    
        Request originalRequest = chain.request();
        Request request;
    
        HttpUrl modifiedUrl = originalRequest.url().newBuilder()
                // Provide your custom parameter here
                .addQueryParameter(key, value)
                .build();
        request = originalRequest.newBuilder().url(modifiedUrl).build();
    
        return chain.proceed(request);
        }
    }

    相关文章

      网友评论

          本文标题:Retrofit2 — 参数拦截器

          本文链接:https://www.haomeiwen.com/subject/yjqusttx.html