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. 一分钟了解:String & StringBuilder & StringBuffer

    这三个都是字符串对象,本篇就来分析下它们的使用途径,力求简单明了. 一.String String 长度是不可变的,如果你要改变string对象的字符或者是拼接字符的话,系统就会新建一个string, ...

  2. ImageView中scaleType属性详解

    scaleType是指定图片的拉伸方式的一个属性,下面是具体的示例和介绍: <LinearLayout xmlns:android="http://schemas.android.co ...

  3. GDSL 1.7 发布,C语言通用数据结构库

    GDSL 1.7 修复了 interval-heap 模块的一个小 bug. GDSL (通用数据结构库) 包含一组程序用于操作各种数据结构.这是一个可移植的库,完全由 ANSI C 编写.为 C 开 ...

  4. 【翻译自mos文章】Windows平台下的 Oraagent Memory Leak

    来源于: Oraagent Memory Leak (文档 ID 1956840.1) APPLIES TO: Oracle Database - Enterprise Edition - Versi ...

  5. Win2008建立域时administrator账户密码不符合要求

    在win2008中建立域时,有时会出现administrator账户密码不符合要求的现象,报错会说明目前本地administrator账户不需要密码.这是什么原因造成的呢?原来,目前的2008镜像在网 ...

  6. LeetCode题解:Rotate List

    Rotate List Given a list, rotate the list to the right by k places, where k is non-negative. For exa ...

  7. [leetcode]Triangle @ Python

    原题地址:https://oj.leetcode.com/problems/triangle/ 题意: Given a triangle, find the minimum path sum from ...

  8. 读书笔记,《Java 8实战》,第三章,Lambda表达式

    第一节,Lambda管中窥豹    可以把Lambda表达式理解为简洁地表示可传递的匿名函数的一种方式,它没有名称,但它有参数列表.函数主题和返回值.    本节介绍了Lambda表达式的语法,它包括 ...

  9. Remote Desktop Session中如何触发Ctrl+Alt+Delete?

    Ctrl+Alt+End is a keyboard shortcut used in a Remote Desktop Session to display the security dialog ...

  10. 使用MDS Switch基本命令的一个例子

    笔者有幸摆弄一套vBlock的环境, 刚刚接手, 对其上的很多配置都不了解. 下面我们就例举一下我们通过运行哪些命令来搞清楚我们的UCS是如何连接到VNX storage array上的. 首先, 通 ...