java 如何下载网络图片

CreateTime--2017年9月30日11:18:19

Author:Marydon

说明:根据网络URL获取该网页上面所有的img标签并下载符合要求的所有图片

所需jar包:jsoup.jar

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; /**
* 图片批量下载工具类
* @author Marydon
* @create time 2016-9-3下午2:01:03
* @update time 2017年9月30日11:07:02
* @E-mail:dellshouji@163.com
*/
public class ImgDownloadUtil { /**
* 根据URL获取网页DOM对象
* @param url
* 网址
* @return DOM对象
*/
public static Document getHtmlDocument(String url) {
Document document = null;
URL urlObj = null;
try {
// 1.建立网络连接
urlObj = new URL(url);
// 2.根据url获取Document对象
document = Jsoup.parse(urlObj, 5000);// 单位:毫秒超时时间 } catch (MalformedURLException e) {
System.out.println("世界上最遥远的距离就是没有网,检查设置!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("您的网络连接打开失败,请稍后重试!");
e.printStackTrace();
} return document;
} /**
* 根据URL获取网页源码
* @param url
* 网址
* @return 网页源码
*/
public static String getHtmlText(String url) {
String htmlText = "";
Document document = null;
URL urlObj = null;
try {
// 1.建立网络连接
urlObj = new URL(url);
// 2.根据url获取Document对象
document = Jsoup.parse(urlObj, 5000);// 单位:毫秒超时时间
// 3.根据dom对象获取网页源码
htmlText = document.html();
} catch (MalformedURLException e) {
System.out.println("世界上最遥远的距离就是没有网,检查设置!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("您的网络连接打开失败,请稍后重试!");
e.printStackTrace();
} return htmlText;
} /**
* 操作Dom对象获取图片地址
* @param document
* Dom对象
* @return 图片地址集合
*/
public static List<String> getImgAddressByDom(Document document) {
// 用于存储图片地址
List<String> imgAddress = new ArrayList<String>();
if (null != document) {
// <img src="" alt="" width="" height=""/>
// 获取页面上所有的图片元素
Elements elements = document.getElementsByTag("img");
String imgSrc = "";
// 迭代获取图片地址
for (Element el : elements) {
imgSrc = el.attr("src");
// imgSrc的内容不为空,并且以http://开头
if ((!imgSrc.isEmpty()) && imgSrc.startsWith("http://")) {
// 将有效图片地址添加到List中
imgAddress.add(imgSrc);
}
}
} return imgAddress;
} /**
* 根据网络URL下载文件
* @param url
* 文件所在地址
* @param fileName
* 指定下载后该文件的名字
* @param savePath
* 文件保存根路径
*/
public static void downloadFileByUrl(String url, String fileName, String savePath) {
URL urlObj = null;
URLConnection conn = null;
InputStream inputStream = null;
BufferedInputStream bis = null;
OutputStream outputStream = null;
BufferedOutputStream bos = null;
try {
// 1.建立网络连接
urlObj = new URL(url);
// 2.打开网络连接
conn = urlObj.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// 3.得到输入流
inputStream = conn.getInputStream();
bis = new BufferedInputStream(inputStream); // 文件保存位置
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdirs();
}
// 文件的绝对路径
String filePath = savePath + File.separator + fileName;
File file = new File(filePath);
// 4.
outputStream = new FileOutputStream(file);
bos = new BufferedOutputStream(outputStream);
byte[] b = new byte[1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
System.out.println("info:" + url + " download success,fileRename=" + fileName);
} catch (MalformedURLException e) {
System.out.println("世界上最遥远的距离就是没有网,检查设置");
System.out.println("info:" + url + " download failure");
e.printStackTrace();
} catch (IOException e) {
System.out.println("您的网络连接打开失败,请稍后重试!");
System.out.println("info:" + url + " download failure");
e.printStackTrace();
} finally {// 关闭流
try {
if (bis != null) {// 关闭字节缓冲输入流
bis.close();
} if (inputStream != null) {// 关闭字节输入流
inputStream.close();
}
if (bos != null) {// 关闭字节缓冲输出流
bos.close();
}
if (outputStream != null) {// 关闭字节输出流
outputStream.close();
} } catch (IOException e) {
e.printStackTrace();
}
}
} }

测试

public static void main(String[] args) {
// 1.确定网址
String url = "http://www.cnblogs.com/Marydon20170307/p/7402871.html";
// 2.获取该网页的Dom对象
Document document = getHtmlDocument(url);
// 3.获取该网页所有符合要求的图片地址
List<String> imgAddresses = getImgAddressByDom(document);
String imgName = "";
String imgType = "";
// 4.设置图片保存路径
String savePath = "C:/Users/Marydon/Desktop";
// 5.批量下载图片
for (String imgSrc : imgAddresses) {
// 5.1图片命名:图片名用32位字符组成的唯一标识
imgName = UUID.randomUUID().toString().replace("-", "");
// 5.2图片格式(类型)
imgType = imgSrc.substring(imgSrc.lastIndexOf("."));
imgName += imgType;
// 5.3下载该图片
downloadFileByUrl(imgSrc, imgName, savePath);
}
}
 

java 下载网络图片的更多相关文章

  1. java下载网络图片

    import java.io.DataInputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IO ...

  2. 使用url下载网络图片以及流介绍

    使用url下载网络图片的时候,首先需要建立一个URL对象,然后使用一个输入流获取该URL中的内容.之后使用读取该输入流的内容,使用一个输出流写到本地文件中.最后关闭输入和输出流.下面是一个简单的下载代 ...

  3. android下载网络图片并缓存

    异步下载网络图片,并提供是否缓存至内存或外部文件的功能 异步加载类AsyncImageLoader public void downloadImage(final String url, final ...

  4. Android开发-下载网络图片并显示到本地

    Android下载网络图片的流程是: 发送网络请求->将图片以流的形式下载下来->将流转换为Bitmap并赋给ImageView控件. 注意点 最新的Android系统不可以在主线程上请求 ...

  5. android 下载网络图片并缓存

    异步下载网络图片,并提供是否缓存至内存或外部文件的功能 异步加载类AsyncImageLoader public void downloadImage(final String url, final ...

  6. java下载安装,环境变量,hello world

    1.Java下载安装 网址:http://java.sun.com/javase/downloads/index.jsp win7 64位选择jdk-8u11-windows-x64.exe. 2.环 ...

  7. java下载远程文件到本地

    java下载远程文件到本地(转载:http://www.cnblogs.com/qqzy168/archive/2013/02/28/2936698.html)   /**       * 下载远程文 ...

  8. .Net 使用爬虫下载网络图片到本地磁盘

    准备: 1.新建控制台项目 2.引用System.Drawing类库 3.安装HtmlAgilityPack 1.5.2.0 4.如果不会XPath语法的话,建议简单看下 代码: static voi ...

  9. Windows系统java下载与安装

    Windows系统java下载与安装 一.前言 作者:深圳-风尘 联系方式:QQ群[585499566] 博客:https://www.cnblogs.com/1fengchen1/ 能读懂本文档人: ...

随机推荐

  1. ScrollView滚动条的各种设置

    ScrollView滚动条不显示:android:scrollbars="none"ScrollView滚动条恒显示:android:fadeScrollbars="fa ...

  2. Mysql 和 Postgresql(PGSQL) 对比

    Mysql 和 Postgresql(PGSQL) 对比 转载自:http://www.oschina.net/question/96003_13994 PostgreSQL与MySQL比较 MySQ ...

  3. PHP xhprof性能优化

    xhprof window http://dev.freshsite.pl/php-extensions/xhprof.html http://php.net/manual/en/book.xhpro ...

  4. NAT模式

    NAT NAT模式中,就是让虚拟机借助NAT(网络地址转换)功能,通过宿主机器所在的网络来访问公网. NAT模式中,虚拟机的网卡和物理网卡的网络,不在同一个网络,虚拟机的网卡,是在vmware提供的一 ...

  5. warning: LF will be replaced by CRLF in dubbo-demo-api/pom.xml.

    今天使用git add .的时候出现了一个错误. 错误如下: 解决方案: $ rm -rf .git // 删除.git $ git config --global core.autocrlf fal ...

  6. 混沌分形之朱利亚集(JuliaSet)

    朱利亚集合是一个在复平面上形成分形的点的集合.以法国数学家加斯顿·朱利亚(Gaston Julia)的名字命名.我想任何一个有关分形的资料都不会放过曼德勃罗集和朱利亚集.这里将以点集的方式生成出朱利亚 ...

  7. iOS开发-消息通知机制(NSNotification和NSNotificationCenter)

    iOS中委托模式和消息机制基本上开发中用到的比较多,一般最开始页面传值通过委托实现的比较多,类之间的传值用到的比较多,不过委托相对来说只能是一对一,比如说页面A跳转到页面B,页面的B的值改变要映射到页 ...

  8. iOS开发-iOS8地理位置定位

    现在的App基本上都有定位功能,旅游网站根据定位推荐旅游景点,新闻App通过地理位置推荐当地新闻,社交类的App通过位置交友,iOS中实现以上功能需要一个核心的框架CoreLocation,框架提供了 ...

  9. Laravel SQL 查询语句集锦

    1.从数据表中取得单一数据列 $user= DB::table('users')->where('name','John')->first(); 2.检索表中的所有行 复制代码代码如下: ...

  10. JAVA-Eclipse中web-inf和meta-inf文件夹

    WEB-INF     /WEB-INF/web.xml        你的Web应用程序配置文件,这是一个XML文件,其中描述了 servlet 和其他的应用组件配置及命名规则:  /WEB- IN ...