首页 > 代码库 > jsoup下载图片
jsoup下载图片
package test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class download { public static int num = 0; public static void main(String[] args) throws IOException { Document doc = Jsoup.connect("http://guju.com.cn/photos/new").get(); Elements elements = doc.select("img[src]"); for (Element element : elements) { String imgUrl = element.attr("src"); System.out.println(imgUrl); if (!imgUrl.startsWith("http://")) { imgUrl = "http:" + imgUrl; } new Thread(new download().new DownLoadThread(imgUrl)).start(); } } public class DownLoadThread implements Runnable { private String imgUrl; public DownLoadThread(String url) { this.imgUrl = url; } @Override public void run() { FileOutputStream out = null; HttpURLConnection conn = null; try { URL url = new URL(imgUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5 * 1000); InputStream inputStream = conn.getInputStream(); // imgUrl.replaceAll("\\", "_").replaceAll("http:", ""); String fileName = "e:\\photo\\"+num++ + ".jpg"; out = new FileOutputStream(new File(fileName)); byte[] arr = new byte[1024]; int len = 0; while ((len = inputStream.read(arr)) != -1) { out.write(arr, 0, len); } System.out.println("=====处理完成===="); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (conn != null) { conn.disconnect(); } } } } }
jsoup下载图片
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。