1. 程式人生 > >HttpClient下載圖片不完整的解決辦法

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

最近使用HttpClient爬取網頁,下載圖片,發現很多都有問題,影象只能顯示一半。後來上網搜,找到了解決辦法,如下所述。

 

下載部分的邏輯寫成下面這樣就可以了

public void download(String url) throws HttpException, ClientProtocolException, IOException
{
    String[] filename;
    HttpClient httpClient;
    HttpGet getMethod = new HttpGet(url);
  
    HttpResponse response = httpClient.execute(getMethod);
    //logger.info(response.getStatusLine());
           
    int statusCode = response.getStatusLine().getStatusCode();
           
    if (statusCode == HttpStatus.SC_OK) {
               
        filename = url.split("/"); // 取圖片連結的最後一段為檔名
        File storeFile = new File("E:\\JAVA_programm\\網頁檔案\\images\\" + filename[filename.length-1]
            + ".tmp"); // 先存為臨時檔案,等全部下完再改回原來的檔名
               
        FileOutputStream outputStream = new FileOutputStream(storeFile);
        InputStream inputStream = response.getEntity().getContent();
        byte b[] = new byte[32*1024];
        int j = 0;
  
        while( (j = inputStream.read(b)) != -1 )
        {
            outputStream.write(b,0,j);
        }
  
        if (outputStream != null)
        {
            outputStream.close();
        }
          
        storeFile.renameTo(new File("E:\\JAVA_programm\\網頁檔案\\simplecd_images\\" + filename[filename.length-1]));
        b = null;
        logger.info("圖片-" + filename[filename.length-1] + "-下載完成!!");
    } else {
        logger.error("Something wrong and the code is " + statusCode);
        logger.error("And the wrong page is " + url);
    }
    response = null;
    getMethod.releaseConnection();
}