本文封裝的框架包含了自動解析服務器返回的數據,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中拿到解析好的之前定義的對象,就可以處理業務邏輯了。最近項目要上線,忙成狗,先介紹用法,后期再詳細講解一下原理。