Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Download file with Retrofit 2, OkHttp, Okio and RxJava
import com.squareup.okhttp.ResponseBody;
import okio.BufferedSink;
import okio.Okio;
import retrofit.Response;
import retrofit.http.GET;
import retrofit.http.Query;
import rx.Observable;
interface ApiService {
@GET("/media/download")
Observable<Response<ResponseBody>> download(@Query("id") String id);
}
public Observable<File> download(String id) {
return service.download(id)
.flatMap(this::saveFile);
}
public Observable<File> saveFile(Response<ResponseBody> response) {
return Observable.create((Observable.OnSubscribe<File>) subscriber -> {
try {
// you can access headers of response
String header = response.headers().get("Content-Disposition");
// this is specific case, it's up to you how you want to save your file
// if you are not downloading file from direct link, you might be lucky to obtain file name from header
String fileName = header.replace("attachment; filename=", "");
// will create file in global Music directory, can be any other directory, just don't forget to handle permissions
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsoluteFile(), fileName);
BufferedSink sink = Okio.buffer(Okio.sink(file));
// you can access body of response
sink.writeAll(response.body().source());
sink.close();
subscriber.onNext(file);
subscriber.onCompleted();
} catch (IOException e) {
e.printStackTrace();
subscriber.onError(e);
}
});
}
@471448446

This comment has been minimized.

Copy link

@471448446 471448446 commented Nov 6, 2016

Is there a way to listener progress of downloading?

@mcwienczek

This comment has been minimized.

Copy link

@mcwienczek mcwienczek commented Apr 23, 2017

Are you sure it's Retrofit 2? Package name is wrong in imports.

@viestursGr

This comment has been minimized.

Copy link

@viestursGr viestursGr commented May 10, 2017

I am interested as well in progress listener!

@sergioborne

This comment has been minimized.

Copy link

@sergioborne sergioborne commented May 22, 2017

What happens when the file is big??. I think with this approach will cause an OOM.

@Kazunka

This comment has been minimized.

Copy link

@Kazunka Kazunka commented Jul 6, 2018

Any way to listen download progress? And can we show the download notification with this?

@mochadwi

This comment has been minimized.

Copy link

@mochadwi mochadwi commented Jan 8, 2019

Up for listen download progress and download notification @lsurvila

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment