簡體   English   中英

ImageIO.read()失敗,沒有異常且URL無效

[英]ImageIO.read() failing with no exception and a vaild url

我有以下代碼,我似乎無一例外地經歷了隨機圖像讀取失敗。 我正在批處理作業中運行以下圖像網址,其他一些網址卻無法運行。 失敗是ImageIO.read為null,盡管它是一個非常好的工作url。 發布的網址是我遇到失敗的網址。 任何人都知道導致此代碼失敗的原因。

我還想說我也在使用Java 8。

   try {            
        URL url;

        url = new URL("https://content.homenetiol.com/672/27185/640x480/4d352f4ff9cf4948a93612e91401e128.jpg");

        BufferedImage sourceImg = ImageIO.read(url);
        System.out.println(sourceImg);

    } catch (MalformedURLException ex) {
        System.out.println("MalformedURLException " + ex.getMessage());
    } catch (IOException ex) {
        System.out.println("IOException " + ex.getMessage());
    }

也是一個有效的網址

https://content.homenetiol.com/672/27185/640x480/49a9236f2196432db81e477fde44e756.jpg

我非常確定,通過curl ,服務器偶爾會響應標准Java URL無法處理的302重定向響應。

這是一些使用Apache HttpClient來獲取圖像的代碼,即使服務器響應302重定向,該代碼也可以正常工作:

try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
  HttpGet httpget = new HttpGet("https://content.homenetiol.com/672/27185/640x480/4d352f4ff9cf4948a93612e91401e128.jpg");
  try (CloseableHttpResponse response = httpclient.execute(httpget);
       InputStream stream = response.getEntity().getContent()) {
    BufferedImage sourceImg = ImageIO.read(stream);
    System.out.println(sourceImg);
  }
} catch (IOException e) {
  e.printStackTrace();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM