安卓 WebView -> 显示 WebArchive

19

自API 11以来,Android的WebView具有saveWebArchive方法:http://developer.android.com/。它可以将整个网站保存为webarchive文件,非常棒!但是我如何将下载的内容放回到WebView中呢?我尝试过

webview.loadUrl(Uri.fromFile(mywebarchivefile));

但那只会在屏幕上显示XML。


1
请查看我的回答,了解如何保存和加载所有API的存档这里 - DeltaCap019
2个回答

26

2014年2月21日更新

我下面发布的回答不适用于在Android 4.4 KitKat及更高版本中保存的Web存档文件。WebView在Android 4.4“KitKat”(可能也适用于更新版本)下的saveWebArchive()方法不会像下面发布的读取代码所示那样将Web存档保存为XML格式。相反,它以MHT(MHTML)格式保存页面。只需使用以下代码即可轻松读取.mht文件:

webView.loadUrl("file:///my_dir/mySavedWebPage.mht");

这样做比以前的方法简单得多,而且兼容其他平台。

之前发布的内容

我自己需要用到这个功能,但是在我搜索过的所有地方,都没有像这样的无解问题。所以我不得不自己开发出这个功能。下面是我的小型WebArchiveReader类以及如何使用它的示例代码。请注意,尽管Android文档声明shouldInterceptRequest()是在API11(Honeycomb)中添加到WebViewClient中的,但是该代码可以在Android模拟器中成功地测试并运行,最低支持API8(Froyo)。以下是所有需要的代码,我还将完整项目上传到GitHub存储库https://github.com/gregko/WebArchiveReader

文件WebArchiveReader.java:

package com.hyperionics.war_test;

import android.util.Base64;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;

public abstract class WebArchiveReader {
    private Document myDoc = null;
    private static boolean myLoadingArchive = false;
    private WebView myWebView = null;
    private ArrayList<String> urlList = new ArrayList<String>();
    private ArrayList<Element> urlNodes = new ArrayList<Element>();

    abstract void onFinished(WebView webView);

    public boolean readWebArchive(InputStream is) {
        DocumentBuilderFactory builderFactory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        myDoc = null;
        try {
            builder = builderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        try {
            myDoc = builder.parse(is);
            NodeList nl = myDoc.getElementsByTagName("url");
            for (int i = 0; i < nl.getLength(); i++) {
                Node nd = nl.item(i);
                if(nd instanceof Element) {
                    Element el = (Element) nd;
                    // siblings of el (url) are: mimeType, textEncoding, frameName, data
                    NodeList nodes = el.getChildNodes();
                    for (int j = 0; j < nodes.getLength(); j++) {
                        Node node = nodes.item(j);
                        if (node instanceof Text) {
                            String dt = ((Text)node).getData();
                            byte[] b = Base64.decode(dt, Base64.DEFAULT);
                            dt = new String(b);
                            urlList.add(dt);
                            urlNodes.add((Element) el.getParentNode());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            myDoc = null;
        }
        return myDoc != null;
    }

    private byte [] getElBytes(Element el, String childName) {
        try {
            Node kid = el.getFirstChild();
            while (kid != null) {
                if (childName.equals(kid.getNodeName())) {
                    Node nn = kid.getFirstChild();
                    if (nn instanceof Text) {
                        String dt = ((Text)nn).getData();
                        return Base64.decode(dt, Base64.DEFAULT);
                    }
                }
                kid = kid.getNextSibling();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean loadToWebView(WebView v) {
        myWebView = v;
        v.setWebViewClient(new WebClient());
        WebSettings webSettings = v.getSettings();
        webSettings.setDefaultTextEncodingName("UTF-8");

        myLoadingArchive = true;
        try {
            // Find the first ArchiveResource in myDoc, should be <ArchiveResource>
            Element ar = (Element) myDoc.getDocumentElement().getFirstChild().getFirstChild();
            byte b[] = getElBytes(ar, "data");

            // Find out the web page charset encoding
            String charset = null;
            String topHtml = new String(b).toLowerCase();
            int n1 = topHtml.indexOf("<meta http-equiv=\"content-type\"");
            if (n1 > -1) {
                int n2 = topHtml.indexOf('>', n1);
                if (n2 > -1) {
                    String tag = topHtml.substring(n1, n2);
                    n1 = tag.indexOf("charset");
                    if (n1 > -1) {
                        tag = tag.substring(n1);
                        n1 = tag.indexOf('=');
                        if (n1 > -1) {
                            tag = tag.substring(n1+1);
                            tag = tag.trim();
                            n1 = tag.indexOf('\"');
                            if (n1 < 0)
                                n1 = tag.indexOf('\'');
                            if (n1 > -1) {
                                charset = tag.substring(0, n1).trim();
                            }
                        }
                    }
                }
            }

            if (charset != null)
                topHtml = new String(b, charset);
            else
                topHtml = new String(b);
            String baseUrl = new String(getElBytes(ar, "url"));
            v.loadDataWithBaseURL(baseUrl, topHtml, "text/html", "UTF-8", null);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private class WebClient extends WebViewClient {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            if (!myLoadingArchive)
                return null;
            int n = urlList.indexOf(url);
            if (n < 0)
                return null;
            Element parentEl = urlNodes.get(n);
            byte [] b = getElBytes(parentEl, "mimeType");
            String mimeType = b == null ? "text/html" : new String(b);
            b = getElBytes(parentEl, "textEncoding");
            String encoding = b == null ? "UTF-8" : new String(b);
            b = getElBytes(parentEl, "data");
            return new WebResourceResponse(mimeType, encoding, new ByteArrayInputStream(b));
        }

        @Override
        public void onPageFinished(WebView view, String url)
        {
            // our WebClient is no longer needed in view
            view.setWebViewClient(null);
            myLoadingArchive = false;
            onFinished(myWebView);
        }
    }
}

以下是如何使用这个类的示例,以MyActivity.java类为例:

package com.hyperionics.war_test;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.IOException;
import java.io.InputStream;

public class MyActivity extends Activity {

    // Sample WebViewClient in case it was needed...
    // See continueWhenLoaded() sample function for the best place to set it on our webView
    private class MyWebClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url)
        {
            Lt.d("Web page loaded: " + url);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        WebView webView = (WebView) findViewById(R.id.webView);
        try {
            InputStream is = getAssets().open("TestHtmlArchive.xml");
            WebArchiveReader wr = new WebArchiveReader() {
                void onFinished(WebView v) {
                    // we are notified here when the page is fully loaded.
                    continueWhenLoaded(v);
                }
            };
            // To read from a file instead of an asset, use:
            // FileInputStream is = new FileInputStream(fileName);
            if (wr.readWebArchive(is)) {
                wr.loadToWebView(webView);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void continueWhenLoaded(WebView webView) {
        Lt.d("Page from WebArchive fully loaded.");
        // If you need to set your own WebViewClient, do it here,
        // after the WebArchive was fully loaded:
        webView.setWebViewClient(new MyWebClient());
        // Any other code we need to execute after loading a page from a WebArchive...
    }
}

为了让事情更完整,这是我的一个小Lt.java类用于调试输出:

package com.hyperionics.war_test;

import android.util.Log;

public class Lt {
    private static String myTag = "war_test";
    private Lt() {}
    static void setTag(String tag) { myTag = tag; }
    public static void d(String msg) {
        // Uncomment line below to turn on debug output
        Log.d(myTag, msg == null ? "(null)" : msg);
    }
    public static void df(String msg) {
        // Forced output, do not comment out - for exceptions etc.
        Log.d(myTag, msg == null ? "(null)" : msg);
    }
}

希望这对你有所帮助。

2013年7月19日更新

有些网页没有指定文本编码的元标签,因此我们上面显示的代码无法正确显示字符。在此代码的GitHub版本中,我现在添加了字符集检测算法,该算法会在这种情况下猜测编码。再次查看https://github.com/gregko/WebArchiveReader

Greg


3
太棒了!我希望有一个内置的解决方案,但是没有的话,这个看起来是一个可靠的替代品。谢谢! - Jouke Waleson
@gregko 谢谢你的 Git 项目,它真的很有帮助,你为我节省了很多时间 :) - Tombeau
@gregko 我的意思是,.warc 是 .webarchive 的缩写,请问你能否在这里检查一下我的问题?https://dev59.com/0nnZa4cB1Zd3GeqPsqf- - Aamirkhan
@Aamirkhan,你能否通过电子邮件或在SO上私信我发送几个.webarchive文件的样本,以便我可以了解它们的真实情况并进行实验吗? - gregko
在chromium webview中使用loadUrl()加载mht文件会导致本地崩溃。有什么解决方案吗? - nubela
显示剩余6条评论

17

我知道这是一个旧帖子,但对于我使用的Xamarin Android来说,这非常有效,感谢上帝,因为我真的不想先将存档转换为非base64编码的字符串! - hvaughan3
在我将“application/x-webarchive-xml”替换为“multipart/related”后,这对我有用,这似乎是新格式存档中正确的类型。但由于javascript错误,webview在显示存档后会挂起 - https://dev59.com/D4bca4cB1Zd3GeqPcvlx - Stan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接