Retrofit2.0 添加log拦截、公共参数

创建retrofit 进行网络请求
Retrofit retrofit = new Retrofit.Builder().client(getOkHttpClient())//使用自己创建的OkHttp
        .baseUrl("http://fy.iciba.com/") // 设置 网络请求 Url
        .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析
        .build();

主要工作都在getOkHttpClient 方法中,实现实现log拦截器以及参数添加拦截器 

private OkHttpClient getOkHttpClient() {
    //获取log拦截器
    HttpLoggingInterceptor logger = getLogger();
    //定制OkHttp
    OkHttpClient.Builder httpClientBuilder = new OkHttpClient
            .Builder();
    //OkHttp进行添加拦截器loggingInterceptor 打印log
    httpClientBuilder.addInterceptor(logger);
    //获取公共参数添加拦截器
    HeadInterceptor headInterceptor = new HeadInterceptor(
            "head");
    //OkHttp进行添加拦截器headInterceptor添加公共参数
    httpClientBuilder.addInterceptor(headInterceptor);

    return httpClientBuilder.build();
}

再看getLogger方法,将okhttp请求log信息以Tag=xiaoqiang打印出来

public HttpLoggingInterceptor getLogger() {
    HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
    //新建log拦截器
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            Log.d("xiaoqiang", "OkHttp====:" + message);
        }
    });
    loggingInterceptor.setLevel(level);
    return loggingInterceptor;

}

添加公共请求参数,实现Interceptor接口

public class HeadInterceptor implements Interceptor {
    private final String Head;

    public HeadInterceptor(String head) {
        Head = head;
    }

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request oldRequest = chain.request();
        // 添加新的参数
        HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
                .newBuilder()
                .scheme(oldRequest.url().scheme())
                .host(oldRequest.url().host())
                .addQueryParameter("Head", Head)
                .addQueryParameter("token", "123456789");

        // 新的请求
        Request newRequest = oldRequest.newBuilder()
                .method(oldRequest.method(), oldRequest.body())
                .url(authorizedUrlBuilder.build())
                .build();
        return chain.proceed(newRequest);
    }
}

结果可以看到log会正常打印并且参数Head 和token会作为参数添加到请求中

结果如下:

 

 

你可能感兴趣的:(安卓)