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. Android5.0 ListView特效的简单实现

    Android5.0中对于动画可所谓是情有独钟,在设计规范中大量展现了listview的动画,其实也就是一个目的:将items动画显示出来.这个看起来很炫的效果,其实实现也蛮简单的,我下面就来用动画简 ...

  2. Java命令学习系列(七)——javap

    javap是jdk自带的一个工具,可以对代码反编译,也可以查看java编译器生成的字节码. 一般情况下,很少有人使用javap对class文件进行反编译,因为有很多成熟的反编译工具可以使用,比如jad ...

  3. Http请求中Content-Type讲解以及在Spring MVC注解中produce和consumes配置详解

    原文地址:  https://blog.csdn.net/shinebar/article/details/54408020 引言: 在Http请求中,我们每天都在使用Content-type来指定不 ...

  4. 【ContestHunter】【弱省胡策】【Round7】

    Prufer序列+高精度+组合数学/DP+可持久化线段树 Magic 利用Prufer序列,我们考虑序列中每个点是第几个插进去的,再考虑环的连接方式,我们有$$ans=\sum_{K=3}^n N^{ ...

  5. Iocomp控件教程之Analog Display—模拟显示控件(优于EDIT控件)

    Analog Display是简洁的显示控件.用于显示指定准确度和单位的模拟值(实数),能够将准确度设置为0.使显示结果为整数. 第一步:建立MFC对话框 第二步:插入AnalogDisplay控件 ...

  6. C#线程同步方法汇总

    我们在编程的时候,有时会使用多线程来解决问题,比如你的程序需要在 后台处理一大堆数据,但还要使用户界面处于可操作状态:或者你的程序需要访问一些外部资源如数据库或网络文件等.这些情况你都可以创建一个子线 ...

  7. window.location属性用法及解决一个window.location.search为什么为空的问题

    通常用window.location该属性获取页面 URL 地址: 1.什么是window.location? 比如URL:http://b.a.com:88/index.php?name=kang& ...

  8. async和await的返回值——NodeJS, get return value from async await

    在ES6和ES5中promise的执行也有不同点(上述提到,ES6中promise属microtask:在ES5中,暂未接触到有api直接操作microtask的,所以.then的异步是用setTim ...

  9. Kafka:ZK+Kafka+Spark Streaming集群环境搭建(六)针对spark2.2.1以yarn方式启动spark-shell抛出异常:ERROR cluster.YarnSchedulerBackend$YarnSchedulerEndpoint: Sending RequestExecutors(0,0,Map(),Set()) to AM was unsuccessful

    Spark以yarn方式运行时抛出异常: [spark@master bin]$ cd /opt/spark--bin-hadoop2./bin [spark@master bin]$ ./spark ...

  10. THINKPHP 错误:Undefined class constant 'MYSQL_ATTR_INIT_COMMAND'

    最近公司同事将我之前使用Thinkphp开发的一个项目从香港迁移到国内阿里云服务器上去,结果网站所有地址打开全部一片空白 跟同事确认了PHP版本,Mysql版本等都是跟迁移前的配置一样的,最终经过我查 ...