25 HttpClient下载图片
生活随笔
收集整理的這篇文章主要介紹了
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下载图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ABAP培训进入SAP第一步
- 下一篇: C语言历史简介