1. 程式人生 > >HttpClient下載圖片

HttpClient下載圖片

主要是一些流操作吧,之前用得少,這次寫了就先儲存起來,程式碼如下:

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.http.HttpEntity;
import org.apache.http.TruncatedChunkException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.alibaba.fastjson.JSONObject;

/**
 * 圖片下載
 * @author xiaowei 2018年3月5日 下午1:42:36
 */
public class DownloadPicH5 {

    private static final String CERT_URL         = "http://***/cifCert/queryCifCert";
    private static final String PIC_URL          = "http://***/show?uniqueKey=";
    private static final String RESOURCE_PATH    = "/home/dev/***.xlsx";
    private static final String ERROR_PATH       = "/home/dev/error.txt";
    private static final String EXAMPLE_PIC_PATH = "/home/dev/example.jpg";
    private static final String PIC_POSTFIX      = ".jpg";
    private static final String PIC_FACE         = "正面" + PIC_POSTFIX;
    private static final String PIC_BACK         = "反面" + PIC_POSTFIX;
    private static final String PIC_HAND         = "手持照" + PIC_POSTFIX;
    private static List<Cust>   errorList        = new ArrayList<>();
    static byte[]               bytes            = new byte[1024];

    // 預載入樣例圖片
    static {
        try {
            InputStream in = new FileInputStream(new File(EXAMPLE_PIC_PATH));
            in.read(bytes);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {

        LinkedBlockingQueue<Cust> queue = new LinkedBlockingQueue<>(230000);
        // ArrayBlockingQueue 為有界佇列
        //        ArrayBlockingQueue<Cust> queue = new ArrayBlockingQueue<>(230000);
        //        List<Cust> list = new ArrayList<>(5000);
        FileInputStream excelFileInputStream = new FileInputStream(RESOURCE_PATH);
        // XSSFWorkbook 就代表一個 Excel 檔案
        // 建立其物件,就開啟這個 Excel 檔案
        XSSFWorkbook workbook = new XSSFWorkbook(excelFileInputStream);
        // 輸入流使用後,及時關閉!這是檔案流操作中極好的一個習慣!
        excelFileInputStream.close();
        // XSSFSheet 代表 Excel 檔案中的一張表格
        // 我們通過 getSheetAt(0) 指定表格索引來獲取對應表格
        // 注意表格索引從 0 開始!
        XSSFSheet sheet = workbook.getSheetAt(0);
        // 開始迴圈表格資料,表格的行索引從 0 開始
        // employees.xlsx 第一行是標題行,我們從第二行開始, 對應的行索引是 1
        // sheet.getLastRowNum() : 獲取當前表格中最後一行資料對應的行索引
        String str;
        for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {

            // XSSFRow 代表一行資料
            XSSFRow row = sheet.getRow(rowIndex);
            if (row == null) {
                continue;
            }
            XSSFCell nameCell = row.getCell(0);
            str = nameCell.getStringCellValue();
            //            queue.add(new Cust(str, str.substring(str.length() - 19, str.length())));
            queue.put(new Cust(str, str.substring(str.length() - 19, str.length())));

        }
        // 操作完畢後,記得要將開啟的 XSSFWorkbook 關閉
        workbook.close();

        final CountDownLatch latch = new CountDownLatch(128);
        for (int i = 0; i < 128; i++) {
            new Thread(new Runnable() {
                public void run() {
                    while (!queue.isEmpty()) {
                        // 儲存圖片
                        getPicInfo(queue);
                    }
                    latch.countDown();
                }
            }).start();
        }
        latch.await();
        System.out.println("SUCCESS");
        // 儲存失敗記錄
        if (!errorList.isEmpty()) {
            String error = JSONObject.toJSONString(errorList);
            File tempFile = new File(ERROR_PATH);
            FileOutputStream outStream = new FileOutputStream(tempFile);
            outStream.write(error.getBytes());
            outStream.close();
        }
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //建立一個Buffer字串 
        byte[] buffer = new byte[1024];
        //每次讀取的字串長度,如果為-1,代表全部讀取完畢 
        int len = 0;
        //使用一個輸入流從buffer裡把資料讀取出來 
        while ((len = inStream.read(buffer)) != -1) {
            //用輸出流往buffer裡寫入資料,中間引數代表從哪個位置開始讀,len代表讀取的長度 
            outStream.write(buffer, 0, len);
        }
        //關閉輸入流 
        inStream.close();
        //把outStream裡的資料寫入記憶體 
        return outStream.toByteArray();
    }

    /**
     * 獲取圖片相關資訊
     */
    public static void getPicInfo(Queue<Cust> queue) {

        Cust cust = queue.poll();
        String path = "/home/dev/h5/" + cust.resNo + "/";
        // 建立資料夾
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        //        // 由於前期除錯程式,所以存在重新下載檔案的情況
        //        // 當三個檔案均存在時,跳過該客戶
        //        String pathIgnore = path + PIC_FACE;
        //        File imageFile = new File(pathIgnore);
        //        boolean fileExist = imageFile.exists();
        //        if (fileExist) {
        //            pathIgnore = path + PIC_BACK;
        //            imageFile = new File(pathIgnore);
        //            fileExist = imageFile.exists();
        //            if (fileExist) {
        //                pathIgnore = path + PIC_HAND;
        //                imageFile = new File(pathIgnore);
        //                fileExist = imageFile.exists();
        //                if (fileExist)
        //                    return;
        //            }
        //
        //        }
        try {

            // 1、get cert fileNo
            String response = null;
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(CERT_URL);
            StringEntity entity = new StringEntity(new Req(cust.custNo).toString(), "UTF-8");
            entity.setContentType("application/json");
            post.setEntity(entity);
            CloseableHttpResponse httpResponse = httpClient.execute(post);
            HttpEntity httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity, "UTF-8");
            List<Cert> certList = JSONObject.parseObject(response).getJSONArray("respData")
                .toJavaList(Cert.class);

            // 2、 download file
            boolean type1Exist = false;
            boolean type2Exist = false;
            boolean type5Exist = false;
            for (Cert cert : certList) {
                HttpGet get = new HttpGet(PIC_URL + cert.fileNo);
                CloseableHttpResponse respose = null;
                switch (cert.certType) {
                    case "1":
                        download(httpClient, get, respose, path, PIC_FACE, cust);
                        type1Exist = true;
                        break;
                    case "2":
                        download(httpClient, get, respose, path, PIC_BACK, cust);
                        type2Exist = true;
                        break;
                    case "5":
                        download(httpClient, get, respose, path, PIC_HAND, cust);
                        type5Exist = true;
                        break;
                    default:
                        break;
                }
            }

            if (!type1Exist) {
                File tempFile = new File(path + PIC_FACE);
                FileOutputStream outStream = new FileOutputStream(tempFile);
                outStream.write(bytes);
                outStream.close();
            }
            if (!type2Exist) {
                File tempFile = new File(path + PIC_BACK);
                FileOutputStream outStream = new FileOutputStream(tempFile);
                outStream.write(bytes);
                outStream.close();
            }
            if (!type5Exist) {
                File tempFile = new File(path + PIC_HAND);
                FileOutputStream outStream = new FileOutputStream(tempFile);
                outStream.write(bytes);
                outStream.close();
            }
        } catch (Exception e) {
            errorDo(cust);
        }
    }

    /**
     * 真正下載並儲存圖片的地方
     */
    public static void download(CloseableHttpClient httpClient, HttpGet get,
                                CloseableHttpResponse response, String path, String name, Cust cust) {

        // 檔案已存在,跳過下載
        File imageFile = new File(path + name);
        if (imageFile.exists()) {
            return;
        }

        try {
            response = httpClient.execute(get);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpEntity entity = response.getEntity();
        try {
            InputStream instream = entity.getContent();
            byte[] data = readInputStream(instream);

            //建立輸出流 
            FileOutputStream outStream = new FileOutputStream(imageFile);
            //寫入資料 
            outStream.write(data);
            //關閉輸出流 
            outStream.close();
        } catch (TruncatedChunkException te) {
            errorDo(cust);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 網路錯誤等下載異常時,呼叫該方法重試下載數次
     * @description 此處程式碼是複製getPicInfo方法,可以提取並優化,暫不做處理了。
     */
    public static void errorDo(Cust cust) {

        // 建立資料夾
        String path = "/home/dev/h5/" + cust.resNo + "/";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        for (int i = 0; i < 3; i++) {
            try {
                // 1、get cert fileNo
                String response = null;
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpPost post = new HttpPost(CERT_URL);
                StringEntity entity = new StringEntity(new Req(cust.custNo).toString(), "UTF-8");
                entity.setContentType("application/json");
                post.setEntity(entity);
                CloseableHttpResponse httpResponse = httpClient.execute(post);
                HttpEntity httpEntity = httpResponse.getEntity();
                response = EntityUtils.toString(httpEntity, "UTF-8");
                List<Cert> certList = JSONObject.parseObject(response).getJSONArray("respData")
                    .toJavaList(Cert.class);

                // 2、 download file
                boolean type1Exist = false;
                boolean type2Exist = false;
                boolean type5Exist = false;
                for (Cert cert : certList) {
                    HttpGet get = new HttpGet(PIC_URL + cert.fileNo);
                    CloseableHttpResponse respose = null;
                    switch (cert.certType) {
                        case "1":
                            download(httpClient, get, respose, path, PIC_FACE, cust);
                            type1Exist = true;
                            break;
                        case "2":
                            download(httpClient, get, respose, path, PIC_BACK, cust);
                            type2Exist = true;
                            break;
                        case "5":
                            download(httpClient, get, respose, path, PIC_HAND, cust);
                            type5Exist = true;
                            break;
                        default:
                            break;
                    }
                }

                if (!type1Exist) {
                    File tempFile = new File(path + PIC_FACE);
                    FileOutputStream outStream = new FileOutputStream(tempFile);
                    outStream.write(bytes);
                    outStream.close();
                }
                if (!type2Exist) {
                    File tempFile = new File(path + PIC_BACK);
                    FileOutputStream outStream = new FileOutputStream(tempFile);
                    outStream.write(bytes);
                    outStream.close();
                }
                if (!type5Exist) {
                    File tempFile = new File(path + PIC_HAND);
                    FileOutputStream outStream = new FileOutputStream(tempFile);
                    outStream.write(bytes);
                    outStream.close();
                }
                return;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        errorList.add(cust);
    }
}

/**
 * 客戶類,儲存客戶的resNo、custNo
 * @author xiaowei 2018年3月5日 上午11:38:10
 */
class Cust {
    String resNo;
    String custNo;

    public Cust(String resNo, String custNo) {
        this.resNo = resNo;
        this.custNo = custNo;
    }

    @Override
    public String toString() {
        return "Cust [resNo=" + resNo + ", custNo=" + custNo + "]";
    }

}

/**
 * 用來包裝作為http請求物件,主要功能是toString方法。
 * @description 可用其他方法實現
 * @author xiaowei 2018年3月5日 上午11:40:02
 */
class Req implements Serializable {

    private static final long serialVersionUID = 1L;
    String                    customerNo;

    public Req(String customerNo) {
        this.customerNo = customerNo;
    }

    public String getCustomerNo() {
        return customerNo;
    }

    public void setCustomerNo(String customerNo) {
        this.customerNo = customerNo;
    }

    @Override
    public String toString() {
        return JSONObject.toJSONString(this);
    }
}

/**
 * 身份資訊類,用來接收客戶的檔案資訊
 * @author xiaowei 2018年3月5日 上午11:41:29
 */
class Cert {
    String id;
    String customerNo;
    String customerName;
    String certType;
    String fileNo;
    String fileDesc;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCustomerNo() {
        return customerNo;
    }

    public void setCustomerNo(String customerNo) {
        this.customerNo = customerNo;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCertType() {
        return certType;
    }

    public void setCertType(String certType) {
        this.certType = certType;
    }

    public String getFileNo() {
        return fileNo;
    }

    public void setFileNo(String fileNo) {
        this.fileNo = fileNo;
    }

    public String getFileDesc() {
        return fileDesc;
    }

    public void setFileDesc(String fileDesc) {
        this.fileDesc = fileDesc;
    }

    @Override
    public String toString() {
        return "Cert [id=" + id + ", customerNo=" + customerNo + ", customerName=" + customerName
               + ", certType=" + certType + ", fileNo=" + fileNo + ", fileDesc=" + fileDesc + "]";
    }

}

相關推薦

HttpClient下載圖片不完整的解決辦法

最近使用HttpClient爬取網頁,下載圖片,發現很多都有問題,影象只能顯示一半。後來上網搜,找到了解決辦法,如下所述。   下載部分的邏輯寫成下面這樣就可以了 public void download(String url) throws HttpException, Cl

HttpClient下載圖片

主要是一些流操作吧,之前用得少,這次寫了就先儲存起來,程式碼如下:import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io

HttpClient下載圖片和向伺服器提交資料例項

使用 HttpClient 需要以下 6 個步驟: 1. 建立 HttpClient 的例項 2. 建立某種連線方法的例項,在這裡是GetMethod。在 GetMethod 的建構函式中傳入待連線的

使用httpclient下載圖片時,url中含有中文字元,導致下載失敗的解決方法

先說解決方法吧: 修改tomcat的server.xml檔案,在Connector標籤中加上URLEncoding引數 <Connector port="8080" maxThreads="150" minSpareThreads="25" maxSpareThre

使用httpclient下載 頁面、圖片

body exce cookies pecs final tostring pro sta tor 代碼 import java.io.IOException; import java.io.UnsupportedEncodingException; import or

通過Apache的httpClient的get方式連線伺服器下載圖片到本地

要用Apache的包,必須新增這些包進去才可以。下載後解壓後,放入程式的libs中。 客戶端程式: package lgx.java.test; import java.io.File; import java.io.FileOutputStream; import java.io.IOExcept

使用HttpClient下載網路圖片

最近公司業務需求,需要去XX網站爬取資料,爬取速度過快時,會導致當前IP被封鎖,讓使用者輸入驗證碼。目前使用OCR識別圖片驗證碼並提交,故需要下載驗證碼圖片,研究了一下終於給實現了。在這裡分享一下,希望對大家有用! DownloadPictureTest類 packag

httpclient+asynctask下載圖片並儲存在本地

1、httpclient過時, 在Android studio中可以這樣設定再使用: useLibrary 'org.apache.http.legacy' 2、許可權: <!--許可權--> <use

python 下載圖片(urllib)

下載圖片 python urllib 下載圖片利用urlib庫中的urlretrieve函數import urllib imgurl = "http://ww1.sinaimg.cn/bmiddle/9150e4e5ly1fgo6vvwz5bj20i50fltam.jpg"#把下載的圖片保存在‘/

自動下載圖片的腳本

ces com ons string wget for ring pre current 很多年前,自己寫的,自己的文件丟失了,神奇的網絡讓我又找到了 #!/bin/bash #Description: # download national geographi

這是一個轉載,關於python的下載 圖片視頻

python 爬蟲 python2 python3 urllib 資源 下載目的:再熟悉下python強大的數據處理能力和python2,3的區別情景:貼吧上的圖片,數據結構龐大的xml,某些國外比較火熱的資源分享平臺,你喜歡的漫畫,想看的電影,只要資源不錯,python‘都可以幫你實現查找,連接下載。原理:

多線程下載圖片,滑動tableView崩潰--資源搶奪問題

http 事情 對象 理解 練習 blog 記錄 下載 ima 最近練習使用NSoperation模擬SDWebImage下載圖片,發生了崩潰的問題,還專門寫博客記錄這件事情: http://www.cnblogs.com/tufei7/p/7074030.html, 當時

遠程下載圖片

req 遠程 lose name strtol web pat amp oot function get_url_image($url){ $ext = explode(‘.‘, $url); $ext = strtolower(end($ext)); i

從網頁下載圖片的代碼

pen puts nload pre clas 網頁 except orm lex import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOExcepti

Python 下載圖片的幾種方法

load color quest content 利用 pytho get .com 圖片 總結下: url = ‘http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1707/31/c14/54293429_

php遠程下載圖片

extension ext nts php 真的 tin 如果 == 失敗 這一天上班真的累啊,趁著這會閑寫個抓取圖片的碼子。話不多少上代碼!! 1 <?php 2 //要抓取的網址; 3 $url = ‘http://www.zixue.it/‘; 4

Web 下載圖片為空

tails 開始 .com log 從服務器 代碼 進行 csdn 成了 問題描述: 文件下載功能是web開發中經常使用到的功能,使用HttpServletResponse對象就可以實現文件的下載。但是下載任務正常進行,下載下來的圖片卻是空 問題代碼:

利用urllib下載圖片

原理 src .cn http ima pen 技術分享 eve 打開 # 爬蟲項目原理:打開網址---獲取源碼---找到圖片---匹配取出## urllib模塊:urlopen打開---read源碼# urlretrieve保存到文件,下載 利用urllib下載圖片

php下載圖片到本地

commons 測試的 lod aws == ani posit anim cat 寫了一天,就寫了這麽點代碼,湊後用吧。 <?php/** * @filename saveImage.php */ function getImgName($url) { i

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