retrofit2 下载文件以及FileCallBack里获取下载进度

首先是接口定义 

public interface UrlService {

    //通用下载
    @Streaming //添加这个注解用来下载大文件
    @GET()
    Call<ResponseBody> downloadFile(@Url String fileUrl);

}

 然后是FileCallBack的写法

import android.content.Context;
import android.os.AsyncTask;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class FileCallBack implements Callback<ResponseBody> {


    private String destFileDir; //存储地址
    private String destFileName; //存储文件名

    public FileCallBack(Context context, String destFileName) {
        this.destFileName = destFileName;
        destFileDir = context.getFilesDir().getAbsolutePath();
    }

    public FileCallBack(String destFileDir, String destFileName) {
        this.destFileDir = destFileDir;
        this.destFileName = destFileName;
    }


    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        new DownloadAsync(destFileDir,destFileName).execute(response.body());
    }


    class DownloadAsync extends AsyncTask<ResponseBody, Progress, Progress> {

        private String destFileDir; //存储地址
        private String destFileName; //存储文件名

        public DownloadAsync(String destFileDir, String destFileName) {
            this.destFileDir = destFileDir;
            this.destFileName = destFileName;
        }

        @Override
        protected Progress doInBackground(ResponseBody... responseBodies) {
            Progress progress = new Progress();

            ResponseBody body = responseBodies[0];
            File file = new File(destFileDir + File.separator + destFileName);
            FileOutputStream fos = null;
            InputStream is;

            progress.fileName = file.getName();
            progress.filePath = file.getPath();

            try {
                progress.status = Progress.LOADING;
                progress.totalSize = body.contentLength();
                fos = new FileOutputStream(file);
                is = body.byteStream();
                byte[] buffer = new byte[8192];

                int len;
                long downloaded = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    downloaded += len;
                    progress.downloadedSize = downloaded;
                    publishProgress(progress);
                }
                fos.flush();
                progress.status = Progress.FINISH;
                is.close();
                fos.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                progress.status = Progress.ERROR;
            } catch (IOException e) {
                e.printStackTrace();
                progress.status = Progress.ERROR;
            }
            return progress;
        }


        @Override
        protected void onProgressUpdate(Progress... values) {
            super.onProgressUpdate(values);
            onProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Progress progress) {
            super.onPostExecute(progress);
            if(progress.status == Progress.FINISH)
            onSuccess(new File(progress.filePath),progress);
        }
    }

    public abstract void onSuccess(File file, Progress progress);
    public abstract void onProgress(Progress progress);

    public class Progress {
        public static final int NONE = 0;         //无状态
        public static final int WAITING = 1;      //等待
        public static final int LOADING = 2;      //下载中
        public static final int PAUSE = 3;        //暂停
        public static final int ERROR = 4;        //错误
        public static final int FINISH = 5;       //完成

        public long totalSize = 0;
        public long downloadedSize = 0;
        public String fileName;
        public String filePath;
        public int status;
        public String url;
        public String tag;
    }

}

 

使用方法:

 new Retrofit.Builder()
                .baseUrl(Api.baseUrl)
                .build()
                .create(UrlService.class)
                .downloadFile("文件下载地址")//可以是完整的地址,也可以是baseurl后面的动态地址
                .enqueue(new FileCallBack(this,"文件名+后缀") {
                    @Override
                    public void onSuccess(File file, Progress progress) {
                        System.out.println(file.getAbsoluteFile());
                        System.out.println(progress.status);
                    }

                    @Override
                    public void onProgress(Progress progress) {
                        System.out.println("文件总大小:"+progress.totalSize);
                        System.out.println("当前下载量:"+progress.downloadedSize);
                        System.out.println("下载进度:"+((float)progress.downloadedSize/(float)progress.totalSize));
                    }

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

                    }
                });

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Retrofit 下载文件需要定义一个返回类型为 `Call<ResponseBody>` 的 Retrofit 接口,其中 `ResponseBody` 表示响应体,它可以包含文件数据。下面是一个简单的示例代码: ```java public interface FileDownloadService { @GET("file/download") Call<ResponseBody> downloadFile(@Query("fileUrl") String fileUrl); } ``` 然后,你可以在应用程序中使用这个接口来下载文件。下面是一个使用 Retrofit 下载文件的示例: ```java String fileUrl = "https://example.com/file.pdf"; Call<ResponseBody> call = fileDownloadService.downloadFile(fileUrl); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccessful()) { // 获取文件数据 ResponseBody body = response.body(); try { InputStream inputStream = body.byteStream(); // 创建文件 File file = new File(Environment.getExternalStorageDirectory(), "file.pdf"); FileOutputStream outputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.flush(); outputStream.close(); inputStream.close(); // 下载完成 Log.d(TAG, "Download completed!"); } catch (IOException e) { e.printStackTrace(); } } else { Log.d(TAG, "Download failed!"); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.e(TAG, "Download failed: " + t.getMessage()); } }); ``` 在这个示例中,我们首先创建了一个 Retrofit 接口 `FileDownloadService`,然后使用这个接口下载文件。在响应成功时,我们从响应体中获取文件数据,并将其写入存储设备中的文件。在响应失败时,我们打印一条日志消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值