httpclient4下載圖片 java實現
有時候需要從網上抓取一下圖片jpg、png等,也可以抓取zip等,這樣就需要寫程式才能達到想要的效果,
下面是用httpclient4做一個工具類,非常的好用
package com.wamei.tool; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.util.UUID; import com.wamei.util.ImageUtil; import com.wamei.util.JsonResponseHelper; import com.wamei.util.SystemConstants; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.log4j.Logger; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; /** * Created by qixuan.chen on 2016/8/18. */ public class ImageDownloadUtil { private static final Logger logger = Logger.getLogger(ImageDownloadUtil.class); public static String download(HttpServletRequest request,String url, String savePath, Integer width, Integer height) { HttpClient httpclient = new DefaultHttpClient(); String picSrc = ""; String picType = url.substring(url.lastIndexOf(".")+1,url.length()); String fileName = UUID.randomUUID().toString().replace("-", "")+"."+picType; String path = request.getSession().getServletContext().getRealPath(savePath+fileName); File storeFile = null; try { HttpGet httpget = new HttpGet(url); //偽裝成google的爬蟲 httpget.setHeader("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"); // Execute HTTP request logger.info("executing request: " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); storeFile = new File(path); FileOutputStream output = new FileOutputStream(storeFile); // 得到網路資源的位元組陣列,並寫入檔案 HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { byte b[] = new byte[1024]; int j = 0; while( (j = instream.read(b))!=-1){ output.write(b,0,j); } output.flush(); output.close(); } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection immediately. httpget.abort(); throw ex; } finally { // Closing the input stream will trigger connection release try { instream.close(); } catch (Exception ignore) {} } if (storeFile.exists()) { BufferedImage newImage = ImageUtil.getFileImage(storeFile, width, height); ImageIO.write(newImage, picType, storeFile); picSrc = "http://"+ JsonResponseHelper.serverAddress+"/wamei/"+savePath+fileName; } } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { httpclient.getConnectionManager().shutdown(); } return picSrc; } public static void main(String[] args) throws MalformedURLException { //抓取下面圖片的測試 //ImageDownloadUtil.download("http://blog.goyiyo.com/wp-content/uploads/2012/12/6E0E8516-E1DC-4D1D-8B38-56BDE1C6F944.jpg", "d:/aaa.jpg"); } }
參考程式碼:
package com.yododo.fds.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.log4j.Logger; public class JpgDownloadUtil { /** * Logger for this class */ private static final Logger logger = Logger.getLogger(JpgDownloadUtil.class); public static void download(String url, String filePathName) { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet(url); //偽裝成google的爬蟲JAVA問題查詢 httpget.setHeader("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"); // Execute HTTP request System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); File storeFile = new File(filePathName); FileOutputStream output = new FileOutputStream(storeFile); // 得到網路資源的位元組陣列,並寫入檔案 HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { byte b[] = new byte[1024]; int j = 0; while( (j = instream.read(b))!=-1){ output.write(b,0,j); } output.flush(); output.close(); } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection immediately. httpget.abort(); throw ex; } finally { // Closing the input stream will trigger connection release try { instream.close(); } catch (Exception ignore) {} } } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { httpclient.getConnectionManager().shutdown(); } } public static void main(String[] args) throws MalformedURLException { //抓取下面圖片的測試 JpgDownloadUtil.download("http://blog.goyiyo.com/wp-content/uploads/2012/12/6E0E8516-E1DC-4D1D-8B38-56BDE1C6F944.jpg", "c:/aaa.jpg"); } }
相關推薦
httpclient4下載圖片 java實現
有時候需要從網上抓取一下圖片jpg、png等,也可以抓取zip等,這樣就需要寫程式才能達到想要的效果, 下面是用httpclient4做一個工具類,非常的好用 package com.wamei.tool; import java.awt.image.BufferedIm
iOS後臺下載圖片並實現本地通知(Swift)
有的時候我們需要APP進入後臺後能夠自動下載更新一些東西所以這裡就說下iOS程式的後臺下載任務,前面的部落格說過要想進行後臺任務就要在plist檔案中進行註冊,這裡註冊Required background modes選項,值是App downloads con
web版使用者通過瀏覽器下載圖片java後臺程式碼
/** * web版使用者通過瀏覽器下載圖片 */ @RequestMapping(value = "webDownloadImg/{imgId}", method = RequestMethod.GET) public @Respons
PDF轉圖片Java實現
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>fontbox</artifactId> <v
Java實現的有道雲筆記圖片批量下載工具
有朋友問我每天哪裡找時間寫這麼多文章。 作為一個程式設計師,當然要善於利用各種工具提高自己做事情的效率了。如果沒有現成的工具,就得自己造。 我寫文章一般是在雲筆記裡編輯,完成之後直接複製貼上到自媒體平臺。我有一個需求,能夠把雲筆記裡包含的所有圖片批量下載到本地某個資料夾裡,這樣我
Java+Jquery實現批量下載圖片實戰
Web端的批量下載圖片實戰 因為客戶提需求必須要圖片的批量下載功能,只能硬著頭皮做,公司還沒有前端,好吧…前後端一條龍操作。畢竟第一次做批量下載圖片,懵逼在所難免,整整花了3天,走了不少彎路,一定要記錄下來。 首先,如何實現批量下載功能。我的第一反應就是,獲取一堆Id然
java實現下載網路伺服器上的附件/圖片到本地
新人小白一枚,記錄下工作中遇到的一點問題和解決方案。僅供自己以後複習參考之用。歡迎大神指導,交流。剛開始學寫部落格,不好的地方請委婉的指出來哦。先來說說需求背景使用java來實現從網站網頁獲取內容(抓取網頁)。可能會遇到以下兩種情況(我暫時就只是遇到了這兩種情況)。1、jav
Java實現URL下載圖片到本地
功能:輸入圖片URL地址和圖片名字,輸出下載圖片到指定目錄。參考程式碼如下: import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.
Java實現圖片的上傳以及下載 Tomcat伺服器
上傳頁面的程式碼: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C/
java實現從url路徑中下載pdf文檔到本地
clas filename input 自己 lis pdf import tin -a package com.cellstrain.icell.util;import java.io.*;import java.net.*;public class DownloadPd
Java實現FTP文件與文件夾的上傳和下載
連接 rem odi 一個 nec stat mod plog erlang Java實現FTP文件與文件夾的上傳和下載 FTP 是File Transfer Protocol(文件傳輸協議)的英文簡稱,而中文簡稱為“文傳協議”。用於Int
java實現pdf按頁切分成圖片
access win for tac sts println ech java col package com.ces.component.pictrueCut.entity; import java.awt.Image; import java.awt.Rectan
Java HttpURLConnection 下載圖片 圖片全是“加密圖片”文字,怎麽解決?
int add tput read args ioe void zip lang package com.qzf.util;import java.io.FileOutputStream;import java.io.IOException;import java.io.I
Java實現多線程下載、斷點續傳
get import 服務 結束 parseint RR range turn con 開三個線程下載,代碼: package demo; import java.io.InputStream; import java.io.RandomAccessFile; impo
java實現連線vsftpd伺服器,上傳,下載,刪除。
核心程式碼如下: package com.bh.service; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOExcep
pdf及word右上角新增圖片(Java實現)
以下程式碼,如有問題,請大家不吝指出,如有更優實現方案,歡迎一起討論。 最近在做一個需求:在pdf和word右上角新增一個二維碼 其中,pdf可以靈活實現二維碼的位置,但是word由於我是在頁首處新增的圖片,因此我的方法只能在頁首處新增圖片。 首先定義一個介面(先丟擲Exception,
Java實現FTP伺服器檔案的上傳和下載
一、前言: 最近剛好需要實現這個功能:實現ftp的上傳和下載。在網上找了下資料,總結了下。直接上程式碼: 二、程式碼示例: 首先使用到的maven依賴: <dependency> <groupId>commons-ne
JAVA實現網頁快照 存為圖片格式
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!  
Java實現圖片等比例縮圖
參考:Java實現圖片等比例縮圖 程式碼:SpringBoot版:https://gitee.com/Yenn-2017_admin/java_proportional_thumbnails 優點: 提升程式效能,提高程式效率 實現方式介紹 案例介紹 實現
Java實現FTP伺服器上傳、下載、下載多個寫入本地、刪除
場景:需要從FTP伺服器一個檔案目錄下down下來所有的檔案,上傳到專案某個目錄下。 上傳下載刪除獲取檔案下所有檔案,順便加上獲取到所有檔案進行下載。 package a1; /** * 1----public boolean uploadFile(String path ,Fi