Home » Android » android – Download Video from Url using Retrofit

android – Download Video from Url using Retrofit

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am using Retrofit for consuming web services and so far its great. But does Retrofit provide a way to download videos from URLs?

I checked this link but the @Streaming annotation is not available anymore.Retro fit Image download

How to&Answers:

Yes you can use the @Streaming annotation which is available as of version 1.6.0. Make sure you use that version.

As specified in the changelog:
New: @Streaming on a Response type will skip buffering the body to a byte[] before delivering.

interface Api {        
    @Get("path/to/your/resource") 
    @Streaming
    Response getData();
}

You should then be able to stream directly from the InputStream like so

Response response = api.getData()
InputStream is = response.getBody().in();
// stream your data directly from the InputStream!

Keep in mind that my example is synchronous for simplicity.

Answer:

To complete @Miguel Lavigne answer here is how to do it with Retrofit 2 :

interface Service {
    @GET("path/to/your/resource")
    @Streaming
    Call<ResponseBody> getData();
}


Call<ResponseBody> call = service.getData();
try {
    InputStream is = call.execute().body().byteStream();
    (...)
} catch (IOException e) {...}