如何获取将在webview中加载的页面的HTML代码?

时间:2011-11-18 06:44:05

标签: android html android-webview

我有一个Android应用程序,我需要获取将在webview中加载的页面的HTML代码。这个代码我甚至需要在webview中加载页面之前得到它并采取相应的行动。

我正在尝试捕获将在方法中加载的URL

“public void onPageStarted(WebView视图,String url,Bitmap favicon)”

但是获取将在webview中加载的页面的HTML代码的方法是什么?

3 个答案:

答案 0 :(得分:2)

使用HttpClient:

public String httpGet(String url) throws URISyntaxException,
       ClientProtocolException, IOException {
      try {

       HttpGet request = new HttpGet();

       request.setURI(new URI(url));
       response = client.execute(request);

       htmlBody = EntityUtils.toString(response.getEntity());

      } catch (Exception ex) {
      }

      return htmlBody;
     }

有两种方法可以在WebView中显示它,或者从文件中显示(然后你应该在设备上保存带有html的文件,这使得内容可以脱机使用):

myWebView.loadUrl("file://"
                                + Environment.getExternalStorageDirectory()
                                + "/filename.html");

或者您使用html:

为WebView提供字符串
myWebView.loadData(HTMLString, "text/html", "utf-8");

在这里你可以找到我写的整个httpClient,你可能需要的一些函数,有些不是:

http://droidsnip.blogspot.com/2011/10/custom-http-client-android.html#more

答案 1 :(得分:0)

我不知道如何获取webview内容,但我将其用于网页代码

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("website url");
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";

BufferedReader reader = new BufferedReader(
    new InputStreamReader(
      response.getEntity().getContent()
    )
  );

String line = null;
while ((line = reader.readLine()) != null){
  result += line + "\n";

}

第二种方法是

 URL url;
    try {
        // url = new URL(data.getScheme(), data.getHost(), data.getPath());
        url = new URL("website url");
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                url.openStream()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            text.append(line);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

答案 2 :(得分:0)

我没有找到任何webview函数来获取HTML数据。我觉得这很有用。

 try {
            URL twitter = new URL(
                    "http://www.stackoverflow.com");
            URLConnection tc = twitter.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    tc.getInputStream()));

            String htmlData = "";
            String line;
            while ((line = in.readLine()) != null) {
                   htmlData = htmlData+"\n"+line;
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }