温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Retrofit+Rxjava如何实现文件上传和下载功能

发布时间:2021-07-10 10:26:02 来源:亿速云 阅读:152 作者:小新 栏目:编程语言

这篇文章主要介绍Retrofit+Rxjava如何实现文件上传和下载功能,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

Retrofit简介:

在Android API4.4之后,Google官方使用了square公司推出的okHttp替换了HttpClient的请求方式。后来square公司又推出了基于okHttp的网络请求框架:Retrofit。

什么是 RxJava?

RxJava 是一个响应式编程框架,采用观察者设计模式。所以自然少不了 Observable 和 Subscriber 这两个东东了。

RxJava 是一个开源项目,地址:https://github.com/ReactiveX/RxJava

还有一个RxAndroid,用于 Android 开发,添加了 Android 用的接口。地址:https://github.com/ReactiveX/RxAndroid

每个应用基本都会涉及到文件的上传或下载,最普遍的一般也就是上传头像或者照片,下载安装包了,本篇文章就这两点简单说一下retrofit+rxjava的对文件的上传和下载。

1.上传

首先说一下单文件上传,一般上传头像等会用到 .

1).写api @Multipart

@POST

( "" )//引号内为地址Observable httpName(@PartMultipartBody.Part file);

2).写presenter的方法

public void httpName(File file) {
RequestBody requestBody = RequestBody. create (MediaType. parse ( "image/png" ), file);
MultipartBody.Part part = MultipartBody.Part. createFormData ( "file" , file.getName() , requestBody);
Observable observable = api. httpName (part);
…rajava+retrofit处理逻辑
}

3)调用方法发起请求

mPresenter. httpName (f);

其中f我为你要上传的文件对象

以图片为例,经过裁剪后将其转化为文件对象方法如下

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Bundle bundle = data.getExtras();
if (bundle != null) {
bitmap = bundle.getParcelable("data");
File f = new File(this.getFilesDir(), (new Date()).getTime() + ".png");
if (f.exists()) {f.delete();}
try {
FileOutputStream out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
f = null;
} catch (IOException e) {
e.printStackTrace();
f = null;
}
if (f != null) {
mPresenter. httpName(f);
}}}//括号可能多或者少,自己添吧

再说一下多文件上传,以及附带有参数的请求,类似这样

mPresenter.httpUpLoadMore(id,phone, File1, File2, File3);
@Multipart
@POST("")
Observable<ResponseBody> httpUpLoadMore (@Query("id") String id, @Query("phone") String phone, @Part MultipartBody.Part file1, @Part MultipartBody.Part file2, @Part MultipartBody.Part file3);

这里附带参数用@FieldMap Map maps也可以,用query好像不太恰当

后面只需要像传单文件一样

RequestBody requestBody1/2/3 = RequestBody.create(MediaType.parse("image/png"), file1/2/3);;
MultipartBody.Part part1/2/3 = MultipartBody.Part.createFormData("file", file1/2/3.getName() , requestBody1/2/3);
Observable bservable= api.httpUpLoadMore(id,phone,part1,part2,part3);
……

2下载

1)写api

@Streaming//下载大文件时需要加上
@GET
Observable > download(@Url String url);

2)Presenter方法

mApi.download (path)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.flatMap(new Func1,Observable>() {
@Override
public Observablecall(Response response) {
boolean b = writeToFile(response, file);//将返回的流转写入到file对象中
final Boolean aBoolean =Boolean.valueOf(b);
return Observable.create(new Observable.OnSubscribe(){
@Override
public void call(Subscriber subscriber) {
try {
subscriber.onNext(aBoolean);
subscriber.onCompleted();
} catch (Exceptione) {
subscriber.onError(ExceptionManager.handleException(e));}}});}})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1(){
@Override
public void call(Boolean bean) {}
}, new Action1(){
@Override
public void call(Throwablethrowable) {}});
[if !supportLineBreakNewLine]
[endif]
private boolean writeToFile(Responsebody,File file) {
try {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[2048];
inputStream =body.body().byteStream();
outputStream = new FileOutputStream(file);
while (true) {
int read =inputStream.read(fileReader);
if (read == -1) break;
outputStream.write(fileReader, 0, read);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}}
} catch (IOException e) {
return false;
}}

3)调用方法发起下载请求

mPresenter.httpToDownload(downPath, file);//file为你下载下来的文件要存放的位置

因本人app中用的是rxjava1,所以一些rxjava+retrofit处理逻辑写的不细甚至有些乱,所以大家可以自己作相应修改,不要拿来就用.

以上是“Retrofit+Rxjava如何实现文件上传和下载功能”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI