如何在 WebView 中获取 POST 请求的 JSON 响应? [英] How can I get the JSON response of a POST request in a WebView?

查看:49
本文介绍了如何在 WebView 中获取 POST 请求的 JSON 响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WebView 带有包含表单(帖子)的 html.单击某个提交按钮时,我会收到 JSON 响应.

I've got a WebView with html containing a form (post). When clicking some submit button I get a JSON response.

我怎样才能得到这个 JSON?

How can I get this JSON?

如果我不拦截请求,json 会显示在 webview 上,所以我想我应该使用 shouldInterceptRequest(我使用的是 API 12),但我不知道如何使用获取其中的 json.

If I don't intercept the request the json is displayed on the webview, so I guess I should use shouldInterceptRequest (I'm using API 12), but I don't know how to get the json in it.

或者也许有更好的方法,比如拦截响应而不是请求?

Or maybe there's a better way, like intercepting the response instead of the request?

mWebView.loadUrl(myURL);  

isPageLoaded = false; // used because the url is the same for the response

mWebView.setWebViewClient(new WebViewClient() {
    @Override
    public WebResourceResponse shouldInterceptRequest (WebView view, String url) {

        if(isPageLoaded){
            // get the json
            return null;
        }
        else return super.shouldInterceptRequest(view, url);
    }

    public void onPageFinished(WebView view, String url) {
        isPageLoaded = true;
    }
});

谢谢

推荐答案

你应该重写 WebViewClient

@Override
public boolean shouldOverrideUrlLoading (WebView view, String url) {

    if(flag) { 

            URL aURL = new URL(url); 
            URLConnection conn = aURL.openConnection(); 
            conn.connect(); 
            InputStream is = conn.getInputStream(); 
            // read inputstream to get the json..
            ...
            ...
            return true;
    }

    return false
}

@override
public void onPageFinished (WebView view, String url) {
    if (url contains "form.html") {
        flag = true;
    }
}

另外看看这个如何如何从 WebView 获取网页内容?

这篇关于如何在 WebView 中获取 POST 请求的 JSON 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆