Skip to content

公共参数

liujingxing edited this page Feb 25, 2023 · 5 revisions

1、公共参数/请求头

通过RxHttpPlugins#setOnParamAssembly(Consumer)方法设置公共参数回调,如下:

RxHttpPlugins.init(OkHttpClient)      //自定义OkHttpClient对象                                                    
    .setOnParamAssembly(new Function<Param<?>, Param<?>>() {  //设置公共参数/请求头回调
        @Override                                                 
        public Param<?> apply(Param<?> p) throws Exception {    
            //主线程执行  
            Method method = p.getMethod();                        
            if (method.isGet()) {     //可根据请求类型添加不同的参数            
            } else if (method.isPost()) {                         
            }                                                     
            p.add("versionName", "1.0.0")//添加公共参数          
                .addHeader("deviceType", "android"); //添加公共请求头    
        }                                                         
    });                                                                          

此时每次发起请求,都会回调传入的Function接口

2、不添加公共参数/请求头

当然,如果希望某个请求不回调该接口,即不添加公共参数/请求头,则可以调用setAssemblyEnabled(boolean)方法,并传入false即可,如下:

RxHttp.get("/service/...")       //get请求 
    .setAssemblyEnabled(false)   //设置是否添加公共参数/头部,默认为true    
    .toObservableString()                  //返回字符串数据    
    .subscribe(s -> {            //这里的s为String类型
        //请求成功                                         
    }, throwable -> {                                  
        //请求失败                                         
    });