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

Android 檔案下載實作(二):打造自己的 HttpUtils 下載工具類

編輯:關於 Android 程式設計

接續上一篇的伺服器端準備,這次要補上客戶端的檔案下載能力。整體流程並不複雜:使用者完成註冊後,App 跳轉到下載頁面;這個頁面只擺了兩個元件——一個用來顯示當前使用者名稱的 TextView,還有一顆下載按鈕。按下按鈕,程式便向伺服器發出請求,把檔案寫進 SD 卡。

順帶一提,本文沒有示範登入畫面,但它的做法與註冊幾乎如出一轍,差別只在伺服器端要多一步「比對資料庫中的帳號與密碼是否相符」。

先把網路請求收進工具類

為了讓 Activity 的程式碼保持清爽,我們把 HTTP 的細節全部封裝到 httpUtils 類別裡。這裡採用 GET 方法,底層交給 HttpURLConnection 負責實際的連線與資料串流。

在 httpUtils 類別中新增 sendDownloadPost 方法,程式碼如下:

public static void sendDownloadPost(URL urls) {
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        // 本文採用 HttpURLConnection,改用 HttpClient 亦可
        HttpURLConnection connection = (HttpURLConnection) urls.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(3000);   // 連線逾時 3 秒
        connection.setReadTimeout(10000);     // 讀取逾時 10 秒
        connection.setDoInput(true);
        connection.setDoOutput(true);

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            Log.d(TAG, "回應正確!!");
            inputStream = new BufferedInputStream(connection.getInputStream());

            // 組出 SD 卡上的檔案路徑
            File file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "A.pdf");
            outputStream = new BufferedOutputStream(new FileOutputStream(file));

            byte[] str = new byte[2048];
            int len = -1;
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                Log.d(TAG, "有權限");
                // 把 inputStream 的內容逐段寫入 SD 卡
                while ((len = inputStream.read(str)) != -1) {
                    outputStream.write(str, 0, len);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); }
        }
        if (outputStream != null) {
            try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); }
        }
    }
}

別忘了權限

這段程式要跑得起來,至少需要三項權限:網路存取、SD 卡讀寫,以及 SD 卡檔案建立。到 AndroidManifest.xml 中補上:

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

進階:讓檔名與伺服器端一致

如果希望下載後的檔名跟伺服器上的原始檔名相同,可以從回應標頭的 Content-Disposition 中取出來。這裡也順手處理了中文亂碼的問題:

String filename = connection.getHeaderField("Content-Disposition");
filename = new String(filename.getBytes("iso8859-1"), "gbk");
filename = filename.split("filename=")[1];

接著把原本寫死的 A.pdf 換成 filename 即可:

File file = new File(Environment.getExternalStorageDirectory() + File.separator + filename);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved