retrofit+okhttp+rxjava

来源:互联网 发布:火山中文移动编程官网 编辑:程序博客网 时间:2024/06/07 16:42

1.上传文件

 @Multipart    @POST(API_P_PERSONALDATA)    Flowable<FileBean> uploadfile(@PartMap Map<String, RequestBody> files);

//上传多张图片,文件,单张图片,单个语音等    public void uploadFile( ResourceSubscriber<FileBean> subscriber, List<File> files, File picfile, File voiceFile,String name) {        LinkedHashMap<String, RequestBody> bodyMap = new LinkedHashMap<>();        if(files!=null&&files.size()>0){            for (int i = 0; i < files.size(); i++) {                bodyMap.put("pic"+"["+i+"]\"; filename=\""+files.get(i).getName(),RequestBody.create(MediaType.parse(Constant.IMG_MEDIATYPE),files.get(i)));            }        }        if (voiceFile != null) {            bodyMap.put("fileVoice\"; filename=\"" + voiceFile.getName(), RequestBody.create(MediaType.parse(Constant.MULTIPART_FORM_DATA), voiceFile));        }        if(picfile!=null){            bodyMap.put("pic\"; filename=\""+picfile.getName(),RequestBody.create(MediaType.parse(Constant.IMG_MEDIATYPE),picfile));        }        bodyMap.put("token",RequestBody.create(MediaType.parse(Constant.TEXT_FROMDATA),UserInfoBean.getInstance().getToken()));        bodyMap.put("id",RequestBody.create(MediaType.parse(Constant.TEXT_FROMDATA),UserInfoBean.getInstance().getUid()));        if(!TextUtils.isEmpty(name)){            bodyMap.put("name",RequestBody.create(MediaType.parse(Constant.TEXT_FROMDATA),name));        }        Flowable observable = httpService.uploadfile(bodyMap);        toSubscribe(observable, subscriber);    }

2.返回字符串

 @FormUrlEncoded    @POST(API_P_INDEX)    Flowable<ResponseBody> pIndex(@FieldMap Map<String, String> map);

public void pIndex(Context c, ListCompositeDisposable compositeSubscription, SubscriberListener<ResponseBody> subscriberOnNextListener,boolean isShow) {    Map<String,String> params = new HashMap<>();    params.put("token", UserInfoBean.getInstance().getToken());    params.put("id",UserInfoBean.getInstance().getUid());    Flowable<ResponseBody> observable = httpService.pIndex(StringUtils.sortMapByValue2(params));    ResourceSubscriber subscriber = new ProgressSubscriber(subscriberOnNextListener, c, -1,isShow);    toSubscribe(observable, subscriber);    compositeSubscription.add(subscriber);}
private void getData(){    if(!UserInfoBean.getInstance().isLogin()){        return;    }    HttpMethods.getInstance().pIndex(mContext, getComp(), new SubscriberListener<ResponseBody>() {        @Override        public void onNext(ResponseBody responseBody, int httpcode) {            try {                String data = responseBody.string().trim();                SimpleBean bean = GsonUtil.GsonToBean(data,SimpleBean.class);                if(bean.state== HttpMethods.HTTP_SUCCESS){                    PersonInfoBean bean1 = GsonUtil.GsonToBean(data,PersonInfoBean.class);                                   }else{                    ToastUtil.makeShortText(mContext,bean.message);                }            } catch (IOException e) {                e.printStackTrace();            }        }        @Override        public void onError(int httpcode) {        }    },false);}
3.下载文件

/** * 下载文件 */private void loadFile() {    initNotification();    if (retrofit == null) {        retrofit = new Retrofit.Builder();    }    Call<ResponseBody> responseBodyCall = retrofit.baseUrl(BASE_URL)            .client(initOkHttpClient())            .build()            .create(HttpService.class)            .loadFile(url);    downCalls.put(url,responseBodyCall);    responseBodyCall.enqueue(new FileCallback(new ListCompositeDisposable(),APK_DOWN_PATH, filename) {                @Override                public void onSuccess(File file) {                    //Log.e("zs", "请求成功");                    // 安装软件                    cancelNotification();                    if(filename.endsWith(".apk")){                        installApk(file);                    }                }                @Override                public void onLoading(long progress, long total) {                   // Log.e("zs", progress + "----" + total);                    if(total==0){                        total = 100;                    }                    updateNotification(progress * 100 / total);                }                @Override                public void onFailure(Call<ResponseBody> call, Throwable t) {                    Log.e("zs", "请求失败");                    cancelNotification();                }            });}
4.7.0适配

public class FileProvider7 {    public static Uri getUriForFile(Context context, File file) {        Uri fileUri = null;        if (Build.VERSION.SDK_INT >= 24) {            fileUri = getUriForFile24(context, file);        } else {            fileUri = Uri.fromFile(file);        }        return fileUri;    }    private static Uri getUriForFile24(Context context, File file) {        Uri fileUri = android.support.v4.content.FileProvider.getUriForFile(context, APP_ID+".FileProvider",                file);        return fileUri;    }    public static void setIntentDataAndType(Context context,                                            Intent intent,                                            String type,                                            File file,                                            boolean writeAble) {        if (Build.VERSION.SDK_INT >= 24) {            intent.setDataAndType(getUriForFile(context, file), type);            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);            if (writeAble) {                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);            }        } else {            intent.setDataAndType(Uri.fromFile(file), type);        }    }    public static void setIntentData(Context context,                                     Intent intent,                                     File file,                                     boolean writeAble) {        if (Build.VERSION.SDK_INT >= 24) {            intent.setData(getUriForFile(context, file));            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);            if (writeAble) {                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);            }        } else {            intent.setData(Uri.fromFile(file));        }    }    public static void grantPermissions(Context context, Intent intent, Uri uri, boolean writeAble) {        int flag = Intent.FLAG_GRANT_READ_URI_PERMISSION;        if (writeAble) {            flag |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;        }        intent.addFlags(flag);        List<ResolveInfo> resInfoList = context.getPackageManager()                .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);        for (ResolveInfo resolveInfo : resInfoList) {            String packageName = resolveInfo.activityInfo.packageName;            context.grantUriPermission(packageName, uri, flag);        }    }    public static void grantPermissions2(Context context, Intent intent, Uri contentUri) {        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {            ClipData clip =                    ClipData.newUri(context.getContentResolver(), "A photo", contentUri);            intent.setClipData(clip);            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);        } else {            List<ResolveInfo> resInfoList =                    context.getPackageManager()                            .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);            for (ResolveInfo resolveInfo : resInfoList) {                String packageName = resolveInfo.activityInfo.packageName;                context.grantUriPermission(packageName, contentUri,                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION);            }        }    }

原创粉丝点击