从android的webview访问JSON响应

时间:2015-03-04 06:02:10

标签: java android json webview

在Android上,我有webView。我正在加载url。首先,我获得Facebook的登录页面,在填写登录详细信息后,它会在同一JSON Response上为我webView提供。

我正在使用此代码加载URL,但现在我不知道如何在JSON Response中获得string我完成的url 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:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');"); } }; wb = (WebView) findViewById(R.id.webview); wb.getSettings().setJavaScriptEnabled(true); wb.getSettings().setSupportZoom(true); wb.getSettings().setBuiltInZoomControls(true); wb.setWebViewClient(yourWebClient); wb.loadUrl("http://pqrs.abcde.com/facebook"); }}

JSON Response

{"status":"success","msg":"You have successfully logged in."} 的格式为:

{{1}}

2 个答案:

答案 0 :(得分:18)

构建一个名为MyJavaScriptInterface的类。和WebView的MyJavaScriptInterface。

    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" +
                    "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
        }
    };
    wb = (WebView) findViewById(R.id.webview);
    wb.getSettings().setJavaScriptEnabled(true);
    wb.getSettings().setSupportZoom(true);
    wb.getSettings().setBuiltInZoomControls(true);
    wb.setWebViewClient(yourWebClient);
    wb.loadUrl("http://pqrs.abcde.com/facebook");
    wb.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");

    class MyJavaScriptInterface {

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

    @JavascriptInterface
    public void showHTML(String html) {
        System.out.println(html);
    }

}

注意:从中你需要删除wb.loadUrl中的窗口(“javascript:...”);. 和“public void showHTML”之前的@JavascriptInterface。

您可以在html参数中从showHtml(..)获取内容。

答案 1 :(得分:0)

    webView.setWebViewClient(new myWebClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(webdata);
}

public class myWebClient extends WebViewClient {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        view.loadUrl(url);
        return true;

    }
}