how to get html content from a webview?

后端 未结 12 1545
鱼传尺愫
鱼传尺愫 2020-11-22 04:29

Which is the simplest method to get html code from a webview? I have tried several methods from stackoverflow and google, but can\'t find an exact method. Please mention an

12条回答
  •  粉色の甜心
    2020-11-22 05:09

    Android will not let you do this for security concerns. An evil developer could very easily steal user-entered login information.

    Instead, you have to catch the text being displayed in the webview before it is displayed. If you don't want to set up a response handler (as per the other answers), I found this fix with some googling:

    URL url = new URL("https://stackoverflow.com/questions/1381617");
    URLConnection con = url.openConnection();
    Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
    Matcher m = p.matcher(con.getContentType());
    /* If Content-Type doesn't match this pre-conception, choose default and 
     * hope for the best. */
    String charset = m.matches() ? m.group(1) : "ISO-8859-1";
    Reader r = new InputStreamReader(con.getInputStream(), charset);
    StringBuilder buf = new StringBuilder();
    while (true) {
      int ch = r.read();
      if (ch < 0)
        break;
      buf.append((char) ch);
    }
    String str = buf.toString();
    

    This is a lot of code, and you should be able to copy/paster it, and at the end of it str will contain the same html drawn in the webview. This answer is from Simplest way to correctly load html from web page into a string in Java and it should work on Android as well. I have not tested this and did not write it myself, but it might help you out.

    Also, the URL this is pulling is hardcoded, so you'll have to change that.

提交回复
热议问题