How do I get the web page contents from a WebView?

后端 未结 7 1828
北恋
北恋 2020-11-22 06:19

On Android, I have a WebView that is displaying a page.

How do I get the page source without requesting the page again?

It seems WebView

7条回答
  •  囚心锁ツ
    2020-11-22 07:15

    Have you considered fetching the HTML separately, and then loading it into a webview?

    String fetchContent(WebView view, String url) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse response = httpClient.execute(get);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        HttpEntity entity = response.getEntity();
        String html = EntityUtils.toString(entity); // assume html for simplicity
        view.loadDataWithBaseURL(url, html, "text/html", "utf-8", url); // todo: get mime, charset from entity
        if (statusCode != 200) {
            // handle fail
        }
        return html;
    }
    

提交回复
热议问题