您的位置:首页 > 理论基础 > 计算机网络

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

2015-08-19 10:59 459 查看
// 下载媒体文件

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();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: