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

(3)下载网络文件

2016-03-08 16:50 597 查看
Java版:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class DownloadFile {
/**
* 批量下载url文件,默认文件名称为系统当前时间
* @param urlList 文件下载链接
* @param filePath 保存路径
* @param fileType 文件后缀名
*/
public static void download(ArrayList<String> urlList,String filePath,String fileType){
File dir = new File(filePath);
if(!dir.exists())
dir.mkdir();
String  name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
String file=filePath+"/"+name+"."+fileType;
for (String urlStr : urlList) {
download(urlStr,file);
}
}

/**
* 下载url文件
* @param urlStr 文件下载链接
* @param file 保存路径
*/
public static void download(String urlStr,String file){
URL url = null;
int responseCode = -1;  //网页返回信息吗
HttpURLConnection con = null;
try {
url = new URL(urlStr);
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");// IE代理进行下载
con.setConnectTimeout(60000);  //连接超时设置为60s即一分钟
con.setReadTimeout(60000);//网页停留时间
//con.setDoOutput(true);
// 获得网页返回信息码
responseCode = con.getResponseCode();
if (responseCode == -1) {
System.out.println(url.toString() + " : connection is failure...");
con.disconnect();
}
if (responseCode >= 400) // 请求失败
{
System.out.println("请求失败:get response code: " + responseCode);
con.disconnect();
}
//获取网页源代码
InputStream in = con.getInputStream();
FileOutputStream out= new FileOutputStream(file);
byte[] buffer = new byte[1204];
int bytesum = 0;
int byteread = 0;
while ((byteread = in.read(buffer)) != -1) {
bytesum += byteread;
out.write(buffer, 0, byteread);
}
System.out.println(file+"文件的字节长度为:"+bytesum);
in.close();
out.flush();
out.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String args[]){
String url="http://i2.dpfile.com/2006-03-15/26040_b.jpg";
String file="./test.jpg";
download(url,file);
}
}


Python版:

利用urllib库的urlretrieve()函数就可以下载网络资源了,有四个参数,不过一般用前两个就可以了,第一个参数是url链接,第二个参数是文件的保存路径。

#!/usr/bin/python
#-*- coding: utf-8 -*-
import urllib
url='http://i2.dpfile.com/2006-03-15/26040_b.jpg'
file='test.jpg'
urllib.urlretrieve(url,file)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: