利用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();
}
}
}
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();
}
}
}
相关文章推荐
- Tomcat HTTPS
- TCP和UDP的区别(转)
- iOS网络请求
- HTTP协议图片上传交互
- 子网划分的两个例子 怎么算网络号和广播地址
- 8月18日“.我爱你”域名总量:紫田网络排名跌至第十八
- TCP/IP、Http的区别
- 解决 schema_reference.4: Failed to read schema document 'http://www.springframework.org/schema/context
- [MFC学习笔记]--网络编程实际操作编写服务器端
- CentOS系统基于网络的PXE+Kickstart无人值守批量安装操作系统(二)
- Android与服务器端数据交互(http协议整合struts2+android)
- [MFC学习笔记]--网络编程理论知识
- TCP建立连接与释放连接过程中的几个问题
- TCP/IP详解 卷I:协议 のping和traceroute
- iOS 网络请求,参数中字典嵌套字典
- TCP/IP TIME_WAIT状态原理
- iOS 带cookie进行网络请求
- hdu 4292 Food【拆点网络流】
- Android Http请求方法汇总
- HTTP状态码详解