生活随笔
收集整理的這篇文章主要介紹了
使用HttpClient下载网络图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近公司業務需求,需要去XX網站爬取數據,爬取速度過快時,會導致當前IP被封鎖,讓用戶輸入驗證碼。目前使用OCR識別圖片驗證碼并提交,故需要下載驗證碼圖片,研究了一下終于給實現了。在這里分享一下,希望對大家有用!
DownloadPictureTest類
package com.yulore.checkcode;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;/*** 下載圖片工具類* * @author bingbing feng 2013-03-14* */
public class DownloadPictureTest {/*** @param args*/public static void main(String[] args) {String uid = "871170f2-2598-48e5-9ee8-58ed6379d8931d2ec8";String s = "1363239309732";String fileName = "ex2.png";getCheckCodePicFromXX(uid,s,fileName);}private static void getCheckCodePicFromXX(String uid, String s,String fileName) {String url = "http://wap.xxx.com//p/ex.d?u_id="+uid+"&m=gvcd&s="+s;String dirPath = "D:/OCR_EX/";downloadPicture(url, dirPath, fileName);}/*** 從網絡上下載圖片*/public static void downloadPicture(String url, String dirPath,String filePath) {DefaultHttpClient httpclient = new DefaultHttpClient();HttpGet httpget = new HttpGet(url);httpget.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");httpget.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");try {HttpResponse resp = httpclient.execute(httpget);if (HttpStatus.SC_OK == resp.getStatusLine().getStatusCode()) {HttpEntity entity = resp.getEntity();InputStream in = entity.getContent();savePicToDisk(in, dirPath, filePath);System.out.println("保存圖片 "+filePath+" 成功....");}} catch (Exception e) {e.printStackTrace();} finally {httpclient.getConnectionManager().shutdown();}}/*** 將圖片寫到 硬盤指定目錄下* @param in* @param dirPath* @param filePath*/private static void savePicToDisk(InputStream in, String dirPath,String filePath) {try {File dir = new File(dirPath);if (dir == null || !dir.exists()) {dir.mkdirs();}//文件真實路徑String realPath = dirPath.concat(filePath);File file = new File(realPath);if (file == null || !file.exists()) {file.createNewFile();}FileOutputStream fos = new FileOutputStream(file);byte[] buf = new byte[1024];int len = 0;while ((len = in.read(buf)) != -1) {fos.write(buf, 0, len);}fos.flush();fos.close();} catch (IOException e) {e.printStackTrace();}finally{try {in.close();} catch (IOException e) {e.printStackTrace();}}}}
OK,搞定啦、、、
總結
以上是生活随笔為你收集整理的使用HttpClient下载网络图片的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。