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(); }?
總結
以上是生活随笔為你收集整理的HttpClient下载图片不完整的解决办法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓桌面壁纸_火莹视频桌面:好玩的动态桌
- 下一篇: Adobe Lightroom Clas