Use Retrofit to download files and monitor progress gracefully

Codewords work hard! Please indicate the source!

0. Preface

Recently, the blogger’s project needs to do upload and download functions with progress monitoring, and it is outrageous that in the online blog post, it is actually necessary to create a separate OkHttpClient with interceptor for downloading with progress, and rewrite the ResponseBody, which is simply complicated. Is there any nausea? ! !

So the blogger tried it himself and found that there is no need to rewrite ResponseBody for downloading with progress ! ! !

Now, looking back at those blog posts that have made a lot of effortless work in order to monitor the progress, I will tell you this expression:

Okay, let’s stop here for diss. Now let’s talk about how to gracefully complete the file download with progress.

1. Create RetrofitService

Slightly different from the general Service, you need to add @Streaming annotation to avoid memory overflow;

In addition, because different files are at different addresses, you need to use the @Url annotation to specify the address of the file:

    @Streaming
    @POST
    Call<ResponseBody> downloadFile(@Url String url, @Body DownloadReq downloadReq);

2. Network request

getRetrofitService().downloadFile(fileUrl, downloadReq).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {

                    /** 此处为了省略无关代码,没有在子线程中执行写入操作,没有关闭流
                     *  各位有修养的攻城狮们请不要学我 */

                    ResponseBody body = response.body();
                    long totalLength = body.contentLength();
                    long writenLength = 0;
                    try {
                        //文件写入
                        InputStream inputStream = body.byteStream();
                        File file = new File(fileName);
                        FileOutputStream fileOutputStream = new FileOutputStream(file);
                        int length;
                        byte[] data = new byte[65536];
                        while ((length =inputStream.read(data))!=-1){
                            fileOutputStream.write(data,0,length);
                            writenLength+=length;

                            //在这里进行监听,writenLength就是已写入的字节数,totalLength即文件总大小

                        }
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                } 
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });

Alright, the problem is solved~!

Finally, it is customary to ask for money:

 

Guess you like

Origin blog.csdn.net/u014653815/article/details/87801085
Recommended