直接使用 URLEncoder.encode(url) 對包含特殊字符(如 %7B)的圖片 URL 編碼後,BitmapFactory.decodeStream 仍無法加載圖片。
URLEncoder 會對所有字符編碼,包括 URL 合法的路徑分隔符 / 和已編碼的百分號序列,導致 URL 結構破壞。正確做法是僅對查詢參數值編碼,或直接使用原始 URL 發起 HTTP 請求。
private InputStream openHttpConnection(String urlString) throws IOException {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) throw new IOException("Not HTTP");
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.setInstanceFollowRedirects(true);
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return httpConn.getInputStream();
}
throw new IOException("HTTP error: " + httpConn.getResponseCode());
}
private Bitmap downloadImage(String url) {
try (InputStream in = openHttpConnection(url)) {
return BitmapFactory.decodeStream(in);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
AsyncTask、Thread、协程或第三方庫 OkHttp/Glide/Picasso)。inSampleSize)防止 OOM。