利用HttpURLConnection下载文件的核心代码代码

// 下载媒体文件
    private void downLoad(String urlStr){
        // 创建HashMap,保存下载到的文件信息
        Map map = new HashMap<String, Object>();
        InputStream is = null;
        FileOutputStream fos = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();            
            int len = conn.getContentLength(); // 记录所要下载内容的总字节数
            map.put("length", len);
            is = conn.getInputStream();
            // 创建一个文件对象,文件将被创建到sdcard根目录,文件名为下载开始时间的毫秒数+文件后缀名
            DataInputStream dis = new DataInputStream(is);
            fos = new FileOutputStream("/mnt/sdcard/"+System.currentTimeMillis()+"."+urlStr.substring(urlStr.lastIndexOf(".")+1));
            byte[] buffer = new byte[1024*10]; // 缓冲字节数组
            int actualLen = 0;
            while((actualLen=is.read(buffer)) != -1){
                fos.write(buffer, 0, actualLen);
                currentProgress += actualLen;
                map.put("currentProgress", currentProgress);
                mHandler.obtainMessage(1, map).sendToTarget();
                fos.flush();
            }            
            mHandler.obtainMessage(2).sendToTarget();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {
                    if(fos != null){
                        fos.close();
                    }
                    if(is != null){
                        is.close();
                    }
                    if(conn != null){
                        
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值