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

Android 圖片加載:正確處理 URL 編碼與網絡請求

     編輯:程式設計綜合問答

問題現象

直接使用 URLEncoder.encode(url) 對包含特殊字符(如 %7B)的圖片 URL 編碼後,BitmapFactory.decodeStream 仍無法加載圖片。

原因分析

URLEncoder 會對所有字符編碼,包括 URL 合法的路徑分隔符 / 和已編碼的百分號序列,導致 URL 結構破壞。正確做法是僅對查詢參數值編碼,或直接使用原始 URL 發起 HTTP 請求。

推薦方案:使用 HttpURLConnection 完整流程

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。
  • 生產環境推薦使用成熟圖片加載庫(Glide、Coil、Fresco),自動處理緩存、生命周期、錯誤重試等。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved