Retrofit+Rxjava實現(xiàn)文件上傳和下載功能
Retrofit簡介:
在Android API4.4之后,Google官方使用了square公司推出的okHttp替換了HttpClient的請求方式。后來square公司又推出了基于okHttp的網絡請求框架:Retrofit。
什么是 RxJava?
RxJava 是一個響應式編程框架,采用觀察者設計模式。所以自然少不了 Observable 和 Subscriber 這兩個東東了。
RxJava 是一個開源項目,地址:https://github.com/ReactiveX/RxJava
還有一個RxAndroid,用于 Android 開發(fā),添加了 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)調用方法發(fā)起請求
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);
}}}//括號可能多或者少,自己添吧
再說一下多文件上傳,以及附帶有參數(shù)的請求,類似這樣
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);
這里附帶參數(shù)用@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)調用方法發(fā)起下載請求
mPresenter.httpToDownload(downPath, file);//file為你下載下來的文件要存放的位置
因本人app中用的是rxjava1,所以一些rxjava+retrofit處理邏輯寫的不細甚至有些亂,所以大家可以自己作相應修改,不要拿來就用.
總結
以上所述是小編給大家介紹的Retrofit+Rxjava實現(xiàn)文件上傳和下載功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
相關文章
在SpringBoot中實現(xiàn)線程池并行處理任務的方法詳解
在使用Spring Boot開發(fā)應用程序時,我們經常需要處理一些耗時的任務,例如網絡請求、數(shù)據庫操作或者其他需要花費一定時間的計算任務,本文將介紹如何在Spring Boot中使用線程池來實現(xiàn)任務的并行處理2023-06-06

