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

你可能感兴趣的:(OkHttp3 Interceptor 拦截器的使用 统一追加参数)