網路資源(圖片、JSON、HTML)的下載與顯示是 App 開發的高頻需求。本文提供一套完整、可生產環境使用的方案:封裝 HTTP 連線取得 InputStream、分別實作圖片/文字下載方法、採用 AsyncTask 執行非同步任務並支援進度回呼與 UI 更新,代碼結構清晰,易於擴充為通用網路層基礎。
openHttpConnection(String url) → 回傳 InputStream,統一處理 HTTP 協議、重導向、錯誤碼判斷。downloadImage() 解碼為 Bitmap;downloadText() 讀取字串內容。DownloadImageTask extends AsyncTask,支援多圖批次下載、進度條更新、完成通知。private InputStream openHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) {
throw new IOException("It is not an HTTP connection");
}
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
Log.e("Networking", ex.getLocalizedMessage());
throw new IOException("Error connecting");
}
return in;
}
// 下載圖片 → Bitmap
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = openHttpConnection(url);
bitmap = BitmapFactory.decodeStream(in);
if (in != null) in.close();
} catch (IOException e) {
Log.e("NetworkingActivity", e.getLocalizedMessage());
}
return bitmap;
}
// 下載文字 → String
private String downloadText(String url) {
final int BUFFER_SIZE = 2000;
InputStream is = null;
try {
is = openHttpConnection(url);
} catch (IOException e) {
e.printStackTrace();
return "";
}
InputStreamReader isr = new InputStreamReader(is);
char[] inputBuffer = new char[BUFFER_SIZE];
StringBuilder str = new StringBuilder();
try {
int charRead;
while ((charRead = isr.read(inputBuffer)) > 0) {
str.append(inputBuffer, 0, charRead);
}
is.close();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return str.toString();
}
private class DownloadImageTask extends AsyncTask {
private long imagesCount = 0;
private ProgressBar progressBar;
public DownloadImageTask(ProgressBar pBar) {
this.progressBar = pBar;
}
@Override
protected Long doInBackground(String... urls) {
for (int i = 0; i < urls.length; i++) {
Bitmap imageDownloaded = downloadImage(urls[i]);
if (imageDownloaded != null) {
imagesCount++;
publishProgress(imageDownloaded); // 觸發 onProgressUpdate
try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
return imagesCount;
}
@Override
protected void onProgressUpdate(Bitmap... bitmaps) {
// 顯示最新下載的圖片
ivImg.setImageBitmap(bitmaps[0]);
// 更新進度條(假設最多 10 張)
progressBar.setProgress((int) (imagesCount * 10));
}
@Override
protected void onPostExecute(Long imageDownloaded) {
String msg = "下載完成!共下載 " + imagesCount + " 張圖片";
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
}
String[] imageUrls = {
"https://example.com/img1.jpg",
"https://example.com/img2.jpg"
// ...
};
new DownloadImageTask(progressBar).execute(imageUrls);
AsyncTask 標記棄用,建議遷移至 Kotlin Coroutines + Retrofit/OkHttp 或 RxJava。HttpURLConnection.setConnectTimeout()、setReadTimeout(),並實作指數退避重試機制。onDestroy() 取消任務(task.cancel(true)),避免 Activity 銷毀後更新 UI 導致洩漏。本文示範從零構建網路下載棧的核心邏輯,適合理解底層原理或輕量級專案無法引入大型庫時使用。實際專案中,強烈建議直接採用成熟網路框架(OkHttp + Retrofit + Coroutines),專注於業務邏輯而非重複造輪子。