Retrofit文件下载

本文接原生拦截WebView页面下载链接跳转空白页问题拦截url后使用Retrofit实现文件下载

/**
 * @param baseUrl
 * @param fileNameDecoder
 * @param context
 * describe:请求网络进行文件下载
 */
HttpServerUtils.DownloadFile(baseUrl, fileNameDecoder, YWebActivity.this);
/**
 * author:  HiYoungPeople
 * date:    2022/04/07.
 * describe:网络请求
 */

public class HttpServerUtils {
    /**
     * 文件下载接口
     * @param fileUrl
     * @param fileName
     * @param context
     */
    public static void DownloadFile(String fileUrl, String fileName, Context context) {
        Call<ResponseBody> call = RetrofitUtils.getServiceApi().downloadFile(fileUrl);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                new AsyncTask<Void, Long, String>() {
                    @SuppressLint("StaticFieldLeak")
                    @Override
                    protected String doInBackground(Void... voids) {
                        Log.d("cwf", "DownloadFileSuccess: " + response.toString());
                        try {
                            //响应的ResponseBody转换成byte
                            byte[] bytes = response.body().bytes();

                            FileUtils fileUtils = new FileUtils();
                            String sdpath = fileUtils.getSDPATH();
                            boolean fileExist = fileUtils.isFileExist(sdpath,fileName);
                            if (fileExist) {
                                return "3";
                            } else {
                                //写入文件
                                File file = fileUtils.writeSDFromInput(sdpath, fileName, bytes);
                                Log.d("cwf", "file: " + file);
                            }

                            return "2";
                        } catch (Exception e) {
                            e.printStackTrace();
                            return "1";
                        }

                    }

                    @Override
                    protected void onPostExecute(String result) {
                        super.onPostExecute(result);
                        if ("1".equals(result)){
                            ToastUtils.show(context, "下载失败");

                        }else if ("2".equals(result)){
                            ToastUtils.show(context, "下载成功");

                        }else if ("3".equals(result)){
                            ToastUtils.show(context, "此文件已完成下载");

                        }
                    }
                }.execute();

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                Log.d("cwf", "DownloadFileFailure: " + throwable.toString());

            }
        });


    }
}
/**
 * author:  HiYoungPeople
 * date:    2022/04/07.
 * describe: API接口类
 */

public interface HttpService {

    /**
     *
     *文件下载
     * @param fileUrl
     * @return
     */
    @Streaming
    @GET
    Call<ResponseBody> downloadFile(@Url String fileUrl);
}
/**
 * author:  HiYoungPeople
 * date:    2022/04/07.
 * describe:写入文件工具类
 */
public class FileUtils {

    private String SDPATH;

    public String getSDPATH() {
        return SDPATH;
    }

    //构造函数,得到SD卡的目录,这行函数得到的目录名其实是叫"/SDCARD"
    public FileUtils() {
        SDPATH = Environment.getExternalStorageDirectory() + "/cwf/";
    }

    //在SD卡上创建文件
    public File createSDFile(String fileName) throws IOException {
        File file = new File(SDPATH + fileName);
        file.createNewFile();
        return file;
    }

    //在SD卡上创建目录
    public File createSDDir(String dirName) {
        File dir = new File(dirName);
        dir.mkdir();
        return dir;
    }

    //判断SD卡上的文件夹是否存在
    public boolean isFileExist(String path, String fileName) {
        File file = new File(path + fileName);
        return file.exists();
    }

    //将bytes写入到SD卡中
    //将bytes写到path这个目录中的fileName文件上
    public File writeSDFromInput(String path, String fileName, byte[] bytes) {
        File file = null;
        FileOutputStream output = null;
        try {
            createSDDir(path);
            file = createSDFile(fileName);
            //FileOutputStream写入数据,写入到file这个文件上
            output = new FileOutputStream(file);
            output.write(bytes, 0, bytes.length);
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }
}

完整的实现过程记得加存储权限

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值