(3)下载网络文件
来源:互联网 发布:小米2s3g网络设置 编辑:程序博客网 时间:2024/04/28 03:13
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 urlliburl='http://i2.dpfile.com/2006-03-15/26040_b.jpg'file='test.jpg'urllib.urlretrieve(url,file)
0 0
- (3)下载网络文件
- 网络-大文件下载(0621)
- 网络文件下载器
- Java 网络文件下载
- java 网络文件下载
- 网络下载文件
- 文件下载 监听网络
- 网络下载文件
- 网络下载文件
- java下载网络文件
- 多线程下载网络文件
- 下载网络文件
- iOS网络文件下载
- 网络:文件下载
- 网络:NSURLSession 下载文件
- 网络文件下载
- 网络下载文件封装
- python 网络下载文件
- Codeforces Round #260 (Div. 2) B. Fedya and Maths (数学规律)
- 个人工具集
- RTTI(Run-Time Type Identification)、虚函数和虚基类的实现方式、开销分析及使用指导
- AS和Eclipse的快捷键
- BP神经网络的自适应步长问题
- (3)下载网络文件
- hdu1008
- 命名参数(C#)
- 事务隔离级别小记
- 图
- IM长连接为何要发送心跳包
- (5)正则表达式——Java
- 常用的mysql练习题和答案01
- Leetcode #5 Longest Palindromic Substring 最长回文串 解题小节