首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java URL 獲取圖片位元組:需用 HttpURLConnection 而非 openStream

     編輯:程式設計綜合問答

問題代碼

URL url = new URL("https://example.com/image.jpg");
InputStream in = url.openStream(); // 可能拋出 IOException、無法處理重導向、無連線逾時控制

正確做法:HttpURLConnection

public static byte[] downloadImage(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(10_000); // 10 秒連線逾時
    conn.setReadTimeout(30_000);    // 30 秒讀取逾時
    conn.setInstanceFollowRedirects(true); // 支援 301/302 重導向
    conn.setRequestProperty("User-Agent", "Mozilla/5.0"); // 部分伺服器要求 UA

    int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new IOException("HTTP error code: " + responseCode);
    }

    try (InputStream in = conn.getInputStream();
         ByteArrayOutputStream out = new ByteArrayOutputStream()) {

        byte[] buffer = new byte[8192];
        int len;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        return out.toByteArray();
    } finally {
        conn.disconnect(); // 釋放連線資源
    }
}

關鍵差異

特性URL.openStream()HttpURLConnection
連線逾時控制無(預設無限等待)可設定 connect/read timeout
重導向處理依賴預設實作,不可控setInstanceFollowRedirects(true)
請求標頭自訂不可setRequestProperty()
回應碼檢查不可getResponseCode()
資源釋放需手動 closedisconnect() 釋放連線池

現代替代:OkHttp / Retrofit

生產環境強烈建議使用成熟網路庫:

// OkHttp 同步下載
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(urlString).build();
try (Response response = client.newCall(request).execute()) {
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    return response.body().bytes();
}

Android 特別注意

  • 網路請求**不可在主執行緒**執行,需放入 Thread、AsyncTask(已棄用)、ExecutorService、RxJava 或 Coroutines。
  • Manifest 需宣告 <uses-permission android:name="android.permission.INTERNET"/>。
  • Android 9+ 預設禁止明文 HTTP,需在 res/xml/network_security_config.xml 設定 cleartextTrafficPermitted="true" 或全站 HTTPS。

掌握 HttpURLConnection 完整參數配置,是理解上層網路庫運作基礎的關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved