日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

25 HttpClient下载图片

發布時間:2023/12/14 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 25 HttpClient下载图片 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

httpClient對請求回來的response.getEntity()中的contentType和圖片后綴進行比較判斷

?這樣就能下載我們想要的類型的圖片了

@Testpublic void testGetDownloadPicture() {/***@param: []*@return: void*@description: 下載圖片*/String url_str = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic15.nipic.com%2F20110811%2F8029346_082444436000_2.jpg&refer=http%3A%2F%2Fpic15.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1636111937&t=c133a2ec6bef5ad21ce34161aebc3948";//可關閉的httpclient客戶端,相當于你打開一個瀏覽器CloseableHttpClient closeableHttpClient = HttpClients.createDefault();//構造httpget請求對象HttpGet httpGet = new HttpGet(url_str);//響應CloseableHttpResponse response = null;try {response = closeableHttpClient.execute(httpGet);//獲取響應結果 HttpEntity不僅可以作為結果,也可以作為請求的參數實體,有很多實現HttpEntity entity = response.getEntity();// image/jpg image/jpeg image/pngString contentType = entity.getContentType().getValue();//特別注意這里要getValue一下,否則這里不是string類型的數據而是eader類型的String suffix = ".jpeg";if (contentType.contains("jpeg") || contentType.contains("jpg")) {suffix = ".jpg";} else if (contentType.contains("bmp") || contentType.contains("bitmap")) {suffix = ".bmp";} else if (contentType.contains("png")) {suffix = "png";} else if (contentType.contains("gif")) {suffix = "gif";}//字節流byte[] bytes = EntityUtils.toByteArray(entity);String localpath = "D:\\LDS\\MavenDemoProject\\src\\main\\resources\\" + "我用httpclient的Get方式下載的圖片" + suffix;FileOutputStream fos = new FileOutputStream(localpath);fos.write(bytes);//關閉輸出流fos.close();//對HttpEntity操作的工具類:EntityUtils//String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8.name());//System.out.println(toStringResult);//確保流關閉EntityUtils.consume(entity);} catch (Exception e) {e.printStackTrace();} finally {if (closeableHttpClient != null) {try {closeableHttpClient.close();} catch (IOException e) {e.printStackTrace();}}if (response != null) {try {response.close();} catch (IOException e) {e.printStackTrace();}}}}

總結

以上是生活随笔為你收集整理的25 HttpClient下载图片的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。