Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

android - How can I get the JSON response of a POST request in a WebView?

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

How can I get this 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;
    }
});

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should override the shouldOverrideUrlLoading method of 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;
    }
}

Also take a look at this How do I get the web page contents from a WebView?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...