retrofit+okhttp+rxjava

简介: retrofit+okhttp+rxjava

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);
            }
        }
    }


相关文章
|
7月前
|
JSON Java 数据格式
rxjava2+retrofit2
rxjava2+retrofit2
55 1
|
设计模式 API
定制Retrofit
定制Retrofit
125 0
定制Retrofit
|
JSON Java 数据格式
rxjava2+retrofit2 简介
rxjava2+retrofit2 简介
106 0
|
JSON Android开发 数据格式
使用Retrofit + RxJava 网络请求
使用Retrofit + RxJava 网络请求
400 0
使用Retrofit + RxJava 网络请求
|
Android开发 Java JSON
RxJava2 和 Retrofit2 结合使用详解
不讲 rxjava 和 retrofit 而是直接上手 2 了,因为 2 封装的更好用的更多。 1. 观察者模式 常见的 button 点击事件为例,button 是被观察者,listener 是观察者,setOnClickListener 过程是订阅,有了订阅关系后在 button 被点击的时候,监听者 listener 就可以响应事件。
|
缓存 API Android开发
浅谈OkHttp以及Retrofit+RxJava的封装使用
1.为什么我们要使用OkHttp?OkHttp有什么优点?  说OkHttp之前我们先说另外两个网络请求库——HttpUrlConnection和HttpClient。
2218 0
|
Android开发 Java
|
Java Android开发 流计算
|
Java Android开发
Android/Java网络加载框架Retrofit(三)结合RxJava2与RxAndroid2
Android/Java网络加载框架Retrofit(三)结合RxJava2与RxAndroid2 把Retrofit与RxAndroid 2与RxJava 2联合使用,实现一个简单功能:加载一批图片到ListView中。
1471 0
|
缓存 安全 Android开发
OKhttp使用详解(二)
Cookie保存 Cookie的保存也提供了快捷方式,当然也可以通过拦截器自己实现 OkHttpClient okHttpClient = new OkHttpClient.
1932 0
下一篇
DataWorks