OkHttp3 Interceptor 拦截器的使用 统一追加参数

日志拦截器

  • 添加依赖
 compile 'com.squareup.okhttp3:logging-interceptor:3.3.0'
  • 设置
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(httpLoggingInterceptor);

Get请求统一追加参数

public class AppendUrlParamInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        //拿到有信息的buidler
        HttpUrl.Builder builder = request.url().newBuilder();

        //得到新的Url(已经追加好了参数)
        HttpUrl newUrl = builder
                .addQueryParameter("token", "iamtoken")
                .build();

        //利用新的Url 构建新的Request ,并发送给服务器
        Request newRequest = request.newBuilder()
                .url(newUrl)
                .build();

        return chain.proceed(newRequest);
    }
}

Header统一追加参数

public class AppendHeaderParamInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        //核心也是通过newBuilder 拿到Builder
        Headers.Builder builder = request.
                headers().
                newBuilder();

        //统一追加header参数
        Headers newHeader = builder
                .add("header1", "iam header1")
                .build();

        Request newRequest = request.newBuilder()
                .headers(newHeader)
                .build();

        return chain.proceed(newRequest);
    }
}

Post请求body统一追加参数

public class AppenBodyParamsInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        //构建新Body
        RequestBody newBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded")
                , "token=iamtoken");

        Request newRequest = request.newBuilder()
                .post(newBody)
                .build();


        return chain.proceed(newRequest);
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值