使用 URL.getContent() 下載 JPEG 圖片回傳 null,無法建立 Drawable。
URL.getContent() 依賴 ContentHandler 機制,對圖片等二進位內容支援不穩定,常回傳 null。標準做法是直接讀取 InputStream。
public static Drawable downloadDrawable(String urlString) throws IOException {
URL url = new URL(urlString);
try (InputStream is = url.openStream()) {
return Drawable.createFromStream(is, "src");
}
}
public static Drawable downloadDrawable(String urlString) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
try (InputStream is = conn.getInputStream()) {
return Drawable.createFromStream(is, "src");
}
}
throw new IOException("HTTP " + conn.getResponseCode());
}
// build.gradle
implementation "com.squareup.okhttp3:okhttp:4.11.0"
// 使用
suspend fun downloadDrawable(url: String): Drawable? = withContext(Dispatchers.IO) {
val request = Request.Builder().url(url).build()
OkHttpClient().newCall(request).execute().use { response ->
if (!response.isSuccessful) return@use null
response.body?.byteStream()?.let { Drawable.createFromStream(it, "src") }
}
}
AsyncTask/Thread/Coroutine,嚴禁主執行緒。OkHttpClient 內建連線池,重用 TCP 連線。Glide/Coil/Picasso 自動處理記憶體/磁碟快取、生命週期、佔位圖、錯誤重試。
// Glide
Glide.with(context).load(url).into(imageView);
// Coil (Kotlin 協程原生)
imageView.load(url) { crossfade(true) }
優勢:零樣板碼、自動快取、記憶體優化、支援 GIF/WebP、生命週期感知、錯誤佔位圖。
URL.getContent() 不可靠,請改用 InputStream 直接讀取位元組流,生產環境直接整合 Glide/Coil 專業圖片載入庫。