如何从Android中的WebView获取响应

时间:2019-05-09 11:49:07

标签: android html android-webview jsoup

我正在WebView中加载URL,并在登录后返回响应。我想获得该回复并使用该值。

WebView的代码

      final WebView wb = (WebView) findViewById(R.id.wb1);

    WebViewClient yourWebClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            wb.loadUrl("javascript:HtmlViewer.showHTML" +
                    "(document.getElementsByTagName('html')[0].innerHTML);");
        }
    };

    wb.getSettings().setJavaScriptEnabled(true);
    wb.getSettings().setSupportZoom(true);
    wb.getSettings().setBuiltInZoomControls(true);
    wb.setWebViewClient(yourWebClient);
    wb.loadUrl(url);
    wb.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");

}


class MyJavaScriptInterface {

    private Context ctx;

    MyJavaScriptInterface(Context ctx) {
        this.ctx = ctx;
    }

    @JavascriptInterface
    public void showHTML(String html) {
        Log.e("TAG", "showHTML: " + html);

        Document document = Jsoup.parse(html);
        Elements elements = document.select("pre");
        for (Element element : elements) {

            //Save As you want to
            Log.d("TAG", " myHTMLResponseCallback : " + element.attr("connected_id"));

        }
        System.out.println(html);
    }

}

我从服务器得到以下响应:

   {"status":"success","connected_id":"eyuryriufgrg"}

当我将其获取为html时,我得到了:

    <head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">{"status":"success","connected_id":"eyuryriufgrg"}</pre></body>

如何获取“ connected_id”的值。

0 个答案:

没有答案