首页 > 代码库 > 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下载图片