Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

把網頁連同圖片一起保存到本地的實現方案

編輯:Android 開發實例

做離線閱讀功能時,會遇到一個不算難但很瑣碎的需求:把一個帶圖片的網頁下載到本地,並讓它在沒有網絡時也能正常顯示。難點不在保存 HTML,而在於把裡面的圖片鏈路一併改成本地路徑。本文的實現用到了 AQuery 庫來簡化網絡請求。

整體思路

四步:抓取 HTML;用正則把 img 標籤裡的 src 全部找出來並下載;把 HTML 中的鏈路替換成本地文件名;把改寫後的 HTML 寫到磁盤,同時在數據庫裡記一條索引。

HtmlStorageHelper.java

package com.nekocode.xuedao.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.nekocode.xuedao.PublicData;
import com.nekocode.xuedao.PublicData.Subscribe;

public class HtmlStorageHelper {

    private String URL = "https://eduproject.sinaapp.com/fetchurl.php/getcontent/";

    private PublicData pd;
    private AQuery aq;
    private SQLiteDatabase mDB;
    private String mDownloadPath;

    public HtmlStorageHelper(Context context) {
        pd = PublicData.getInstance();
        aq = new AQuery(context);

        mDB = context.openOrCreateDatabase("data.db", Context.MODE_PRIVATE, null);
        mDB.execSQL("create table if not exists download_html("
                + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "content_id TEXT NOT NULL, "
                + "title TEXT NOT NULL)");

        mDownloadPath = pd.mAppPath + "download/";
        File dir_file = new File(pd.mAppPath + "download/");
        if (!dir_file.exists()) {
            dir_file.mkdir();
        }
    }

    /** 保存一個網頁到本地 */
    public void saveHtml(final String id, final String title) {
        if (isHtmlSaved(id)) {
            return;
        }

        aq.ajax(URL + id, String.class, new AjaxCallback<String>() {
            @Override
            public void callback(String url, String html, AjaxStatus status) {
                File dir_file = new File(mDownloadPath + id);
                if (!dir_file.exists()) {
                    dir_file.mkdir();
                }

                // 抓取所有 src="..." 中的鏈路
                Pattern pattern = Pattern.compile("(?<=src=\")[^\"]+(?=\")");
                Matcher matcher = pattern.matcher(html);
                StringBuffer sb = new StringBuffer();

                while (matcher.find()) {
                    String picUrl = matcher.group(0);
                    downloadPic(id, picUrl);
                    // 把鏈路替換成下載後的本地文件名
                    matcher.appendReplacement(sb, formatPath(picUrl));
                }
                matcher.appendTail(sb);
                html = sb.toString();

                writeHtml(id, title, html);
            }
        });
    }

    /** 下載單張圖片 */
    private void downloadPic(String id, String url) {
        File pic_file = new File(mDownloadPath + id + "/" + formatPath(url));
        aq.download(url, pic_file, new AjaxCallback<File>() {
            @Override
            public void callback(String url, File file, AjaxStatus status) {
            }
        });
    }

    /** 寫入 HTML 並登記數據庫 */
    private void writeHtml(String id, String title, String html) {
        File html_file = new File(mDownloadPath + id + "/index.html");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(html_file);
            fos.write(html.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }

        ContentValues values = new ContentValues();
        values.put("content_id", id);
        values.put("title", title);
        mDB.insert("download_html", "_id", values);
    }

    /** 判斷是否已下載過 */
    public boolean isHtmlSaved(String id) {
        File file = new File(mDownloadPath + id);
        if (file.exists()) {
            file = new File(mDownloadPath + id + "/index.html");
            if (file.exists()) {
                return true;
            }
        }
        deleteHtml(id);
        return false;
    }

    public String getTitle(String id) {
        Cursor c = mDB.rawQuery(
                "select * from download_html where content_id=?", new String[]{id});
        if (c.getCount() == 0) {
            return null;
        }
        c.moveToFirst();
        int index1 = c.getColumnIndex("title");
        return c.getString(index1);
    }

    /** 取已經下載好的全部條目 */
    public ArrayList<Subscribe> getHtmlList() {
        Cursor c = mDB.rawQuery("select * from download_html", null);
        ArrayList<Subscribe> list = new ArrayList<Subscribe>();

        if (c.getCount() != 0) {
            c.moveToFirst();
            int index1 = c.getColumnIndex("content_id");
            int index2 = c.getColumnIndex("title");

            while (!c.isAfterLast()) {
                String id = c.getString(index1);
                if (isHtmlSaved(id)) {
                    Subscribe sub = new Subscribe(
                            id,
                            c.getString(index2),
                            Subscribe.FILE_DOWNLOADED);
                    list.add(sub);
                }
                c.moveToNext();
            }
        }
        return list;
    }

    /** 刪除離線內容 */
    public void deleteHtml(String id) {
        mDB.delete("download_html", "content_id=?", new String[]{id});
        File dir_file = new File(mDownloadPath + id);
        deleteFile(dir_file);
    }

    /** 遞歸刪除文件或目錄 */
    private void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    this.deleteFile(files[i]);
                }
            }
            file.delete();
        }
    }

    /** 把 URL 轉成合法的文件名 */
    private String formatPath(String path) {
        if (path != null && path.length() > 0) {
            path = path.replace("\\", "_");
            path = path.replace("/", "_");
            path = path.replace(":", "_");
            path = path.replace("*", "_");
            path = path.replace("?", "_");
            path = path.replace("\"", "_");
            path = path.replace("<", "_");
            path = path.replace("|", "_");
            path = path.replace(">", "_");
        }
        return path;
    }
}

關鍵點拆解

正則表達式。(?<=src=")[^"]+(?=") 用了前後向断言,只捕獲引號內部的 URL 本身,不包含 src=" 和結尾的引號。這樣 appendReplacement 替換時才不會把標籤結構破壞掉。

Matcher.appendReplacement + appendTail 的組合。這是逐段拼接替換結果的標準用法:循環裡把上一個匹配點到當前匹配點之間的原文追加進去,再追加替換內容;循環結束後用 appendTail 補上尾部剩餘部分。比直接對字符串做 replace 更安全,因為它只改寫匹配到的片段。

formatPath 的字符清理。URL 裡的 / : ? * 這些字符在文件名中不合法,統一替換成下劃線,作為本地文件名使用。缺了這一步,File 構造出來雖然不報錯,但實際寫盤會失敗。

數據庫做索引。文件系統只負責存內容,是否已下載、標題是什麼這些元信息放 SQLite 裡查更快。isHtmlSaved 裡還做了一層校正:目錄存在但 index.html 缺失時,順手把髒數據清掉。

需要改進的地方

這個實現是教學用的骨架,直接搬到項目裡前建議補齊幾點:

一是異步與回調。圖片下載和 HTML 寫入應該彙總到一個「全部完成」的節點再通知 UI,否則用戶可能在圖片還沒下完時就打開頁面看到一片空白。

二是存儲位置。示例寫在外部存儲根目錄下,Android 10 以後的分區存儲會直接失敗,應改為 getFilesDir() 或 app 專用外部目錄。

三是正則的局限性。它只能處理最簡單的 img src,遇到懶加載的 data-src、CSS 背景圖、單引號包裹的屬性就會漏掉。如果頁面結構複雜,改用 jsoup 這類 HTML 解析庫會穩妥得多。

四是下載失敗的重試。ajax 回調裡應該檢查 status.getCode(),失敗的圖片記錄下來重試,而不是靜默丟棄。

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