Android download large file using Retrofit Streaming

This post demonstrates how to download a zip file from a given url and save it to android internal storage. More precisely the following code will download the zip file https://github.com/gameplay3d/GamePlay/archive/master.zip and save it to /data/data/com.example.retrofitdownloadzip//games/gameplay3d.zip

1. Make sure the INTERNET permission is granted in the manifest file.

<uses-permission android:name="android.permission.INTERNET"/>

2. Add this line into the dependencies in the gralde file to include retrofit library.

compile 'com.squareup.retrofit2:retrofit:2.1.0'

3. The interface for Retrofit REST service, in this case, the GET, the @Streaming enables the downloading for large file.

public interface RetrofitInterface {
    @Streaming
    @GET
    Call<ResponseBody> downloadFileByUrl(@Url String fileUrl);
}

4. The sample code for downloading the file. This method and the folowing method can dump into an activity class and just call it when a button is clicked…

public void downloadZipFile() {
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://github.com/");
    Retrofit retrofit = builder.client(httpClient.build()).build();
    RetrofitInterface downloadService = retrofit.create(RetrofitInterface.class);
    Call<ResponseBody> call = downloadService.downloadFileByUrl("gameplay3d/GamePlay/archive/master.zip");
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                Log.d(TAG, "Got the body for the file");

                new AsyncTask<Void, Long, Void>() {
                    @Override
                    protected Void doInBackground(Void... voids) {
                        saveToDisk(response.body());
                        return null;
                    }
                }.execute();

            } else {
                Log.d(TAG, "Connection failed " + response.errorBody());
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            t.printStackTrace();
            Log.e(TAG, t.getMessage());
        }
    });
}

5. The sample code for saving the file to android internal storage. This method is being called in the above method.

public void saveToDisk(ResponseBody body) {
    try {
        new File("/data/data/" + getPackageName() + "/games").mkdir();
        File destinationFile = new File("/data/data/" + getPackageName() + "/games/gameplay3d.zip");

        InputStream is = null;
        OutputStream os = null;

        try {
            Log.d(TAG, "File Size=" + body.contentLength());

            is = body.byteStream();
            os = new FileOutputStream(destinationFile);

            byte data[] = new byte[4096];
            int count;
            int progress = 0;
            while ((count = is.read(data)) != -1) {
                os.write(data, 0, count);
                progress +=count;
                Log.d(TAG, "Progress: " + progress + "/" + body.contentLength() + " >>>> " + (float) progress/body.contentLength());
            }

            os.flush();

            Log.d(TAG, "File saved successfully!");
            return;
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, "Failed to save the file!");
            return;
        } finally {
            if (is != null) is.close();
            if (os != null) os.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
        Log.d(TAG, "Failed to save the file!");
        return;
    }
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search