美文网首页
Retrofit与Rxjava封装终结者(一)基本用法

Retrofit与Rxjava封装终结者(一)基本用法

作者: wustor | 来源:发表于2017-03-31 17:28 被阅读1049次

    本文封装的框架包含了自动解析服务器返回的数据,token刷新,异常统一处理,先看看封装后的调用方式,测试用的数据是在One开放的API。

    步骤

    • 定义一个RxUrl对象
        //    ------------服务器地址------------------//
        String SERVER_ADDRESS = "http://rest.wufazhuce.com/";
       
        //GET请求
        @GET("OneForWeb/one/getHpinfo")
        Observable<OneBean> getData(@QueryMap Map<String, String> map);
       
        //POST请求数据
        @FormUrlEncoded
        @POST("OneForWeb/one/getHpinfo")
        Observable<OneBean> postData(@FieldMap Map<String, String> map);
        
        //POST上传图片
        @Multipart  
        @POST("项目的url")
        Observable<CommonBean> evaluatePic(@Part MultipartBody.Part part,@Part("_t") RequestBody token);
    
    • 构造参数
    //GET或POST请求数据
     HashMap<String, String> hashMap = new HashMap<>();
     hashMap.put("strDate", "2017-03-25");
    
    //POST上传图片
             RequestBody tokenBody = RequestBody.create(MediaType.parse("text/plain"), PrefUtils.getString(mContext, Constant.USER_TOKEN, ""));
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), mFileSparse.get(number));
            MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData("file", mFileSparse.get(number).getName(), imageBody);
    
    • 创建一个Observable跟RxSubscriber
    //GET或POST请求数据
            Observable<OneBean> weather = RxRequest.getInstance().getProxy(false).postData(hashMap);
            RxSubscriber subscriber = new RxSubscriber(this, new Callback<OneBean>() {
                @Override
                public void onSuccess(OneBean oneBean) {
                    tvData.setText(oneBean.getHpEntity().getStrContent());
                }
            });
    //POST上传图片
       Observable<CommonBean> observable = RxRequest.getInstance().getProxy(false).evaluatePic(imageBodyPart,tokenBody);
            RxSubscriber subscriber = new RxSubscriber(this, new Callback<CommonBean>() {
                @Override
                public void onNext(CommonBean commonBean) {
               
                }
            });
    
    • 发起请求
      RequestManager.getInstance().sendRequest(weather, subscriber);
    

    调用的时候需要一个Observable对象以及RxSubscriber,然后再OnSuccess中拿到解析好的之前定义的对象,就可以处理业务逻辑了。最近项目要上线,忙成狗,先介绍用法,后期再详细讲解一下原理。

    框架下载地址

    相关文章

      网友评论

          本文标题:Retrofit与Rxjava封装终结者(一)基本用法

          本文链接:https://www.haomeiwen.com/subject/mdmvottx.html