java小工具:通過URL連接爬取資源(圖片)


java語言編寫一個簡單爬取網站圖片工具,實現簡單:

  • 通過 java.net.HttpURLConnection 獲取一個URL連接
  • HttpURLConnection 連接成功返回一個java.io.InputStream,通過InputStream讀取圖片放入到字節數組buff
  • 通過BufferedOutputStream(new FileOutputStream(new File("TEST.jpg"))) 形式 將內存buff里的圖片數據寫入到test.jpg文件中

給出工具類的CatchIMG.java代碼如下:

/**   
* @Title: CatchIMG.java 
* @Package web1203.tools 
* @Description: TODO(用一句話描述該文件做什么) 
* @author penny  
* @date 2017年12月3日 下午9:00:05 
* @version V1.0   
*/
package web1203.tools;

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.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/** 
 * @ClassName: CatchIMG 
 * @Description: 爬取一個指定地址的網絡圖片
 * @author penny
 * @date 2017年12月3日 下午9:00:05 
 * 
 */
public class CatchIMG {

	/**
	 * 
	 * @Title: getImg 
	 * @Description: 通過一個url 去獲取圖片
	 * @param @param url 圖片的連接地址
	 * @param @throws IOException    
	 * @throws
	 */
	public static void getImg(String url) throws IOException{
		long startTime = System.currentTimeMillis();
		URL imgURL = new URL(url.trim());//轉換URL
		HttpURLConnection urlConn = (HttpURLConnection) imgURL.openConnection();//構造連接
		urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36");
		urlConn.connect();
		System.out.println(CatchIMG.class.toString()+":獲取連接="+urlConn.getResponseMessage());
		if(urlConn.getResponseCode()==200){//返回的狀態碼是200 表示成功
			InputStream ins = urlConn.getInputStream(); //獲取輸入流,從網站讀取數據到 內存中
			OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("TEST.jpg")));
			int len=0;
			byte[] buff = new byte[1024*10];//10k緩沖流 視你內存大小而定咯
			
			while(-1!=(len=(new BufferedInputStream(ins)).read(buff))){//長度保存到len,內容放入到 buff
				out.write(buff, 0, len);//將圖片數組內容寫入到圖片文件
//				System.out.println(CatchIMG.class.toString()+":"+len+"byte已經寫入到文件中,內容:  "+new String(buff));
			}
			urlConn.disconnect();
			ins.close();
			out.close();
			System.out.println(CatchIMG.class.toString()+":獲取圖片完成,耗時="+((System.currentTimeMillis()-startTime)/1000)+"s");
		}
	}
	/**
	 * @throws IOException  
	 * @Title: main 
	 * @Description: 測試方法
	 * @throws 
	 */
	public static void main(String[] args) throws IOException {
		CatchIMG.getImg("https://files.cnblogs.com/files/humi/wc.bmp");//
	}

}

測試中要獲取的圖片是這個https://files.cnblogs.com/files/humi/wc.bmp

最終效果

imgraber

*** 一個自己寫的java 爬蟲基於jsoup和swing技術


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM