安卓网上下载 到本地保存 使用框架Retrofit

         关于文件下载,现在用的是Retrofit来实现,关于下载,现在就不需要解析成对象,所以接口中拿到的就是一个Resposebody

 
 
// option 1: a resource relative to your base URL @GET("/resource/example.zip") Call<ResponseBody> downloadFileWithFixedUrl(); // option 2: using a dynamic URL @GET Call<ResponseBody> downloadFileWithDynamicUrlSync(@Url String fileUrl);
   
   

如果你要下载的文件是一个静态资源(存在于服务器上的同一个地点),Base URL指向的就是所在的服务器,这种情况下可以选择使用方案一。正如你所看到的,它看上去就像一个普通的Retrofit 2请求。值得注意的是,我们将ResponseBody作为了返回类型。Retrofit会试图解析并转换它,所以你不能使用任何其他返回类型,否则当你下载文件的时候,是毫无意义的。

第二种方案是Retrofit 2的新特性。现在你可以轻松构造一个动态地址来作为全路径请求。这对于一些特殊文件的下载是非常有用的,也就是说这个请求可能要依赖一些参数,比如用户信息或者时间戳等。你可以在运行时构造URL地址,并精确的请求文件。如果你还没有试过动态URL方式,可以翻到开头,现在我们用的是下载用的 option 2:

一、第一步是进行调用请求进行数据请求下载,下载成流
private void query() {
//        http://route.showapi.com/213-4?showapi_appid=48962&topid=5&showapi_sign=9ad486a2461e47f4b3391171911f5b4b
        //1.创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()

                .baseUrl("http://route.showapi.com/")//主机地址
                .build();
        downloadActivity.retrofitinter retrofitinter = retrofit.create(downloadActivity.retrofitinter.class);
        Call<ResponseBody> call = retrofitinter.downfile("http://sc1.111ttt.com/2017/1/11/11/304112004168.mp3");

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        //请求的结果已经有了在Responsebody里面mp3拿到了
                File future=new File(getExternalFilesDir(null)+File.separator+"Future Studio");
                if(writeFileToSDCard(response.body()))
                {
                    Toast.makeText(downloadActivity.this,"下载成功",Toast.LENGTH_SHORT).show();
                }else
                    {
                        Toast.makeText(downloadActivity.this,"下载失败",Toast.LENGTH_SHORT).show();
                    }

                //2.获取本地地址
            }

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

            }
        });
    }
2.将下载好的保存到本地
private boolean writeFileToSDCard(ResponseBody body) {
        try {
            // todo change the file location/name according to your needs
            File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + "wj.mp3");
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                byte[] fileReader = new byte[4096];
                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;
                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);
                int read;
                while ((read=inputStream.read(fileReader))!=-1 ){

                    outputStream.write(fileReader, 0, read);
                    //统计这个下载的数量
                    fileSizeDownloaded += read;
                   Log.e("msg", "file download: " + fileSizeDownloaded + " of " + fileSize);
                }
                outputStream.flush();
                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }
//这个是全面的下载代码。
public class downloadActivity extends AppCompatActivity {
    private RecyclerView mrycleview;
    private ArrayList<josntop.ShowapiResBodyBean.PagebeanBean.SonglistBean> list1;
    recycleadapter rec;
    private ArrayList<String> data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        // /storage/emulated/0/Android/data/com.wj.administrator.mcz/files这个路径
        Log.e("msg1111",getExternalFilesDir(null).getPath());
        query();
    }
    private void query() {
//        http://route.showapi.com/213-4?showapi_appid=48962&topid=5&showapi_sign=9ad486a2461e47f4b3391171911f5b4b
        //1.创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()

                .baseUrl("http://route.showapi.com/")//主机地址
                .build();
        downloadActivity.retrofitinter retrofitinter = retrofit.create(downloadActivity.retrofitinter.class);
        Call<ResponseBody> call = retrofitinter.downfile("http://sc1.111ttt.com/2017/1/11/11/304112004168.mp3");

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        //请求的结果已经有了在Responsebody里面mp3拿到了
                File future=new File(getExternalFilesDir(null)+File.separator+"Future Studio");
                if(writeFileToSDCard(response.body()))
                {
                    Toast.makeText(downloadActivity.this,"下载成功",Toast.LENGTH_SHORT).show();
                }else
                    {
                        Toast.makeText(downloadActivity.this,"下载失败",Toast.LENGTH_SHORT).show();
                    }

                //2.获取本地地址
            }

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

            }
        });
    }
    //保存本地

    public interface retrofitinter
    {
        @GET()
        Call<ResponseBody> downfile(@Url String fileurl);

    }
    private boolean writeFileToSDCard(ResponseBody body) {
        try {
            // todo change the file location/name according to your needs
            File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + "wj.mp3");
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                byte[] fileReader = new byte[4096];
                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;
                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);
                int read;
                while ((read=inputStream.read(fileReader))!=-1 ){

                    outputStream.write(fileReader, 0, read);
                    //统计这个下载的数量
                    fileSizeDownloaded += read;
                   Log.e("msg", "file download: " + fileSizeDownloaded + " of " + fileSize);
                }
                outputStream.flush();
                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值