Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 檔案下載實作:HttpURLConnection 與串流寫入 SD 卡

編輯:關於 Android 程式設計

幾乎每個 App 遲早都會遇到「從網路抓一個檔案存到本機」的需求:電子書、MP3、圖片、更新包都算。本文示範一个不依賴第三方函式庫的基礎寫法,用 HttpURLConnection 取串流,再逐段寫入外部儲存空間,並把職責拆成三個類別。

整體結構

  • HttpDownloader:下載工具類。download(String urlStr) 處理純文字回應,逐行讀回字串;downfile(String urlStr, String path, String fileName) 處理二進位檔案,回傳整數狀態碼。
  • FileUtils:檔案工具類。負責取得 SD 卡路徑、建立目錄與檔案、判斷檔案是否存在、把輸入流寫進檔案。
  • Download:主介面。兩個按鈕分別觸發文字下載與檔案下載,點擊後另開執行緒處理網路工作。

第一步:權限宣告

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

少了 INTERNET 權限,連線會在建立 socket 時直接失敗;少了寫入權限,檔案會在開啟輸出流時丟出例外。兩者缺一不可。

版面配置

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android_hello word" />

    <Button
        android:id="@+id/buttontxt"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:text="單擊下載 txt 文件" />

    <Button
        android:id="@+id/buttonmp3"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:text="單擊下載 mp3 文件" />
</LinearLayout>

下載工具類 HttpDownloader

public class HttpDownloader {

    private URL url = null;

    /** 下載純文字內容 */
    public String download(String urlStr) {
        StringBuilder sb = new StringBuilder();
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        try {
            url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) try { reader.close(); } catch (IOException ignored) {}
            if (conn != null) conn.disconnect();
        }
        return sb.toString();
    }

    /**
     * 下載二進位檔案
     * @return -1 下載失敗;0 成功;1 檔案已存在
     */
    public int downfile(String urlStr, String path, String fileName) {
        FileUtils fileUtils = new FileUtils();
        if (fileUtils.isExist(path + fileName)) {
            return 1;
        }
        InputStream in = null;
        try {
            in = getFromUrl(urlStr);
            File file = fileUtils.writeToSDPATHFromInput(path, fileName, in);
            return file != null ? 0 : -1;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }

    /** 依 url 取得輸入流 */
    public InputStream getFromUrl(String urlStr) throws IOException {
        url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        return conn.getInputStream();
    }
}

兩個方法背後其實是同一件事——取得 InputStream,差別只在「怎麼消化這個串流」:文字用 BufferedReader 逐行讀,檔案則原封不動寫到磁碟。相較於原範例,這裡補上了逾時設定與 finally 中的資源釋放,這兩點在真實環境中經常是 ANR 與記憶體洩漏的來源。

檔案工具類 FileUtils

public class FileUtils {
    private String SDPATH = null;

    public FileUtils() {
        SDPATH = Environment.getExternalStorageDirectory() + "/";
    }

    public String getSDPATH() { return SDPATH; }

    public File createFile(String fileName) throws IOException {
        File file = new File(SDPATH + fileName);
        file.createNewFile();
        return file;
    }

    public File createDir(String fileName) throws IOException {
        File dir = new File(SDPATH + fileName);
        dir.mkdir();
        return dir;
    }

    public boolean isExist(String fileName) {
        return new File(SDPATH + fileName).exists();
    }

    public File writeToSDPATHFromInput(String path, String fileName,
                                        InputStream inputstream) {
        File file = null;
        OutputStream out = null;
        try {
            createDir(path);
            file = createFile(path + fileName);
            out = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputstream.read(buffer)) > 0) {
                out.write(buffer, 0, length);   // 只寫入實際讀到的長度
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputstream != null) inputstream.close();
                if (out != null) out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
}

這裡有個細節值得留意:迴圈條件必須是 (length = in.read(buffer)) > 0 搭配 out.write(buffer, 0, length)。若直接寫 out.write(buffer),每次都會把整個 1024 位元組寫出去,最後一段沒填满的空白位元組會讓檔案尾端多出一堆垃圾——圖片因此打不開、壓縮檔因此解不開,都是這個原因。

主介面 Download

public class Download extends Activity {
    private Button buttontxt;
    private Button buttonmp3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);

        buttontxt = (Button) findViewById(R.id.buttontxt);
        buttontxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        HttpDownloader hd = new HttpDownloader();
                        String txt = hd.download("https://www.example.com/");
                        Log.i("Download", txt);
                    }
                }).start();
            }
        });

        buttonmp3 = (Button) findViewById(R.id.buttonmp3);
        buttonmp3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        HttpDownloader hd = new HttpDownloader();
                        int result = hd.downfile(
                                "https://www.example.com/demo.jpg",
                                "Android/", "9.jpg");
                        Log.i("Download", "result = " + result);
                    }
                }).start();
            }
        });
    }
}

實務上必須知道的幾件事

  • 主執行緒不能連網:Android 3.0(API 11)之後,在主執行緒發起網路請求會丟出 NetworkOnMainThreadException。所以下載一定要放在背景執行緒,這也是範例為何要包一層 new Thread()。
  • 更新 UI 要回到主執行緒:背景執行緒只能打 Log。若要更新進度條或提示訊息,需透過 Handler、runOnUiThread()、AsyncTask(已不建議)或 Kotlin 協程切回主執行緒。
  • 新版本的儲存權限模型不同:Android 10 起導入分區儲存(Scoped Storage),直接寫入 Environment.getExternalStorageDirectory() 會受限;建議改用 getExternalFilesDir() 取得 App 專屬目錄(不需額外權限),或透過 MediaStore / SAF 存取共享媒體。Android 13 更把媒體權限細分為 READ_MEDIA_IMAGES 等。
  • 要檢查回應碼:getInputStream() 在 4xx/5xx 時會丟例外,正式環境應先取 getResponseCode() 判斷,並用 getErrorStream() 讀取錯誤內容。
  • 路徑要驗證:path + fileName 若直接來自網路回應,可能被塞入 ../ 造成路徑穿越。檔名前應過濾非法字元並強制使用預期目錄。
  • 進度與斷點續傳:需要顯示百分比時,先取 Content-Length 當分母;要支援續傳,則在請求中帶上 Range 標頭並以 append 模式開啟輸出流。
  • 大型下載建議交給系統:下載量級大、需要背景持續進行時,直接使用 DownloadManager 或 WorkManager 會比自行管理執行緒更省事,也能在 App 被關閉後繼續。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved