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

Android 網路檔案下載實作教學:HttpURLConnection 與外部儲存

編輯:關於 Android 程式設計

把遠端資源抓回手機裡

幾乎每個 App 都逃不掉「從伺服器取檔案」這件事,可能是歌詞、音樂、圖片,也可能是設定檔。在 Android 上,最直覺的做法就是走 HTTP:開一條連線、拿到輸入串流,再把內容寫進外部儲存。本文用一個能同時下載歌詞檔與 MP3 的小範例,把整個流程走一遍。

實作前的兩個關鍵決策

一、用 HTTP 把檔案讀成串流

核心只有三件事:建立連線物件、取得輸入串流、以及記得申明網路權限。

  • 建立連線:HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
  • 取得串流:urlConn.getInputStream()
  • 權限:android.permission.INTERNET

二、把串流寫進 SDCARD

下載的目的地通常是外部儲存。取得路徑的方式是 Environment.getExternalStorageDirectory(),對應的權限則是 android.permission.WRITE_EXTERNAL_STORAGE。若要在較新的 Android 版本上執行,還需要一併處理執行期權限的動態申請,這部分不在本範例範圍內,但實務上不可省略。

版面配置

畫面上放兩個按鈕,一個抓歌詞、一個抓音樂。

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下載歌詞" />

    <Button
        android:id="@+id/btn_mp3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_txt"
        android:text="下載 MP3" />
</RelativeLayout>

MainActivity:把耗時工作丟到子執行緒

網路請求絕對不能寫在主執行緒,否則會直接觸發 NetworkOnMainThreadException。因此每個按鈕都對應一個獨立的工作執行緒。

package com.chay.download;

import com.chay.utils.HttpDownloader;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private String urlStr_txt = "https://192.168.56.1:8080/mp3/wan.lrc";
    private String urlStr_mp3 = "https://192.168.56.1:8080/mp3/wan.mp3";
    private String path = "mp3/";
    private String fileName = "wan.mp3";

    private Button downloadTxtButton;
    private Button downloadMp3Button;

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

        downloadTxtButton = (Button) findViewById(R.id.btn_txt);
        downloadTxtButton.setOnClickListener(new DownloadTxtListener());

        downloadMp3Button = (Button) findViewById(R.id.btn_mp3);
        downloadMp3Button.setOnClickListener(new DownloadMp3Listener());
    }

    /** 下載歌詞:文字檔可以直接轉成字串 */
    class DownloadTxtListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            new DownloadTxtThread().start();
        }
    }

    class DownloadTxtThread extends Thread {
        @Override
        public void run() {
            HttpDownloader downloader = new HttpDownloader();
            System.out.println(downloader.download(urlStr_txt));
        }
    }

    /** 下載 MP3:二進位檔要落地成檔案 */
    class DownloadMp3Listener implements OnClickListener {
        @Override
        public void onClick(View v) {
            new DownMp3Thread().start();
        }
    }

    class DownMp3Thread extends Thread {
        @Override
        public void run() {
            HttpDownloader downloader = new HttpDownloader();
            System.out.println(downloader.downFile(urlStr_mp3, path, fileName));
        }
    }
}

HttpDownloader:文字與二進位走兩套路徑

文字檔用 BufferedReader 逐行讀、拼成字串即可;二進位檔則是把串流原封不動地寫到檔案。這個類別刻意分成兩個方法,回傳值約定為:-1 表示失敗、0 表示成功、1 表示檔案已存在。

package com.chay.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpDownloader {

    private URL url = null;

    /** 下載純文字內容並直接回傳字串 */
    public String download(String urlStr) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader buffer = null;
        try {
            url = new URL(urlStr);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            while ((line = buffer.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (buffer != null) buffer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /** -1 失敗;0 成功;1 檔案已存在 */
    public int downFile(String urlStr, String path, String fileName) {
        InputStream inputStream = null;
        try {
            FileUtils fileUtils = new FileUtils();
            if (fileUtils.isFileExist(path + fileName)) {
                return 1;
            }
            inputStream = getInputStreamFromUrl(urlStr);
            File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
            if (resultFile == null) {
                return -1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } finally {
            try {
                if (inputStream != null) inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    public InputStream getInputStreamFromUrl(String urlStr)
            throws MalformedURLException, IOException {
        url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        return urlConn.getInputStream();
    }
}

FileUtils:目錄、檔案與寫入

這個工具類別負責三件事:判斷檔案是否存在、建立目錄與檔案、以及把輸入串流寫進外部儲存。寫入時用 4KB 的緩衝區迴圈搬資料,這是處理大檔最省內存的做法。

package com.chay.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;

public class FileUtils {

    private String SDPATH;

    public String getSDPATH() {
        return SDPATH;
    }

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

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

    public File creatSDDir(String dirName) {
        File dir = new File(SDPATH + dirName);
        dir.mkdirs();
        return dir;
    }

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

    /** 把 InputStream 的內容整份寫進 SDCARD */
    public File write2SDFromInput(String path, String fileName, InputStream input) {
        File file = null;
        OutputStream output = null;
        try {
            creatSDDir(path);
            file = creatSDFile(path + fileName);
            output = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int len;
            while ((len = input.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }
}

小結

整個下載機制其實很樸素:HttpURLConnection 取流、FileOutputStream 落地,中間用執行緒避開主執行緒。真正需要留意的是權限、路徑拼接與串流關閉這三個容易出錯的細節。若要進一步優化,可以加上進度回報、斷點續傳與失敗重試。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved