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

Android 加載網絡圖片到 ImageView:HttpClient 完整流程與異常處理

     編輯:程式設計綜合問答

問題

使用 URLConnection 直接 decodeStream 返回 null,ImageView 空白。

原因

  • 未檢查 HTTP 響應碼,可能為 302 重定向、404、500 等。
  • 未設置 User-Agent,部分服務器拒絕無 UA 請求。
  • 流讀取未關閉,導致連接泄漏。

健壯實現

public static Bitmap downloadBitmap(String urlString) {
    HttpGet request = new HttpGet(urlString);
    request.setHeader("User-Agent", "Android App");
    try (CloseableHttpClient client = HttpClients.createDefault();
         CloseableHttpResponse response = client.execute(request)) {
        int status = response.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) return null;
        HttpEntity entity = response.getEntity();
        if (entity == null) return null;
        try (InputStream is = entity.getContent()) {
            return BitmapFactory.decodeStream(is);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

現代最佳實踐

  • 使用 OkHttp + Glide/Picasso/Coil:自動處理緩存、重試、生命周期、變換、佔位圖。
  • 示例:Glide.with(this).load(url).into(imageView);
  • 若必須手寫,封裝為 Repository 模式,配合协程/RxJava 異步執行。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved