How to realize the function of File upload and download by Retrofit+Rxjava
Today, I would like to share with you the relevant knowledge points about how to achieve file upload and download functions in Retrofit+Rxjava. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.
Introduction to Retrofit:
After Android API4.4, Google officially replaced the request method of HttpClient with okHttp launched by square. Later, square launched a web request framework based on okHttp: Retrofit.
What is RxJava?
RxJava is a responsive programming framework that uses the observer design pattern. So, of course, there are two things: Observable and Subscriber.
There is also a RxAndroid for Android development, adding interfaces for Android.
1. Upload
First of all, talk about single file upload, generally upload avatars will be used.
1)。 Write api @ Multipart
@ POST
("") / / inside the quotation marks is the address Observable httpName (@ PartMultipartBody.Part file)
2)。 The method of writing 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 processing logic}
3) call the method to initiate the request
MPresenter. HttpName (f)
Among them, I am the object of the file you want to upload
Taking a picture as an example, the method of converting it to a file object after cropping is as follows
@ Overrideprotected 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);} / / there may be more or less parentheses. Add them yourself.
Let's talk about multiple file uploads and requests with parameters, like this.
MPresenter.httpUpLoadMore (id,phone, File1, File2, File3); @ Multipart@POST ("") Observable httpUpLoadMore (@ Query ("id") String id, @ Query ("phone") String phone, @ Part MultipartBody.Part file1, @ Part MultipartBody.Part file2, @ Part MultipartBody.Part file3)
The parameter attached here is also fine with @ FieldMap Map maps, but it seems inappropriate to use query.
It just needs to be like a flyer file.
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 download
1) write api
@ Streaming// needs to add @ GETObservable > download (@ Url String url) when downloading large files
2) Presenter method
MApi.download (path) .subscribeOn (Schedulers.io ()) .subscrieOn (Schedulers.io ()) .flatMap (new Func1,Observable > () {@ Overridepublic Observablecall (Response response) {boolean b = writeToFile (response, file); / / write the returned stream to the file object final Boolean aBoolean = Boolean.valueOf (b); return Observable.create (new Observable.OnSubscribe ()) {@ Overridepublic void call (Subscriber subscriber) {try {subscriber.onNext (aBoolean); subscriber.onCompleted () } catch (Exceptione) {subscriber.onError (ExceptionManager.handleException (e));});}}) .subscribe (new Action1 () {@ Overridepublic void call (Boolean bean) {}, new Action1 () {@ Overridepublic 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) call the method to initiate the download request
MPresenter.httpToDownload (downPath, file); / / the location where the downloaded files will be stored for you is all the contents of the article "how to upload and download files in Retrofit+Rxjava". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.