android RxJava+Retrofit2.0 OkHttp添加日志拦截器和设置请求头

添加日志拦截器

        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        //DEBUG模式下 添加日志拦截器
        if(BuildConfig.DEBUG){
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClientBuilder.addInterceptor(interceptor);
        }

设置请求头headers

        //添加一个设置header拦截器
        //header User-Agent 设备系统/app版本号(设备的系统版本号;设备型号)
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request mRequest = chain.request().newBuilder()
                        .header("User-Agent","android/" +
                                App.VERSIONNAME + "(" +
                                DeviceUtils.getSDKVersion() + ";" +
                                DeviceUtils.getModel() + ")")
                        .build();
                return chain.proceed(mRequest);
            }
        });

最后添加Retrofit
mRetrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())





你可能感兴趣的:(android笔记)