17

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

Jonik
  • 80,077
  • 70
  • 264
  • 372
jul
  • 36,404
  • 64
  • 191
  • 318

3 Answers3

9

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?

Community
  • 1
  • 1
Ron
  • 24,175
  • 8
  • 56
  • 97
  • It does not work because the url is the same as the one with the form, and with your solution I get the html with the form. Instead of intercepting the request, I should intercept the response before displaying it in the webview, or send the request with the post params... – jul Apr 23 '12 at 13:13
  • You should ignore the form page and catch the next page loading... The doc says "Gives the host application a chance to take over the control when a new url is about to be loaded in the current WebView." So you should set a flag when form load completes, and catch the immediate next loading that happens.. – Ron Apr 23 '12 at 13:25
  • Dont compare the url.. set a flag to know when the form is loading and when json is loading.. – Ron Apr 23 '12 at 13:27
  • The flag ´isPageLoaded´ does exactly what you say: when true I'll get the json. The url is the same: the form is sent with POST data. Also I must use `shouldInterceptRequest` because shouldOverrideUrlLoading is never called. – jul Apr 23 '12 at 14:35
  • Ok.. but you cannot use `shouldInterceptRequest` coz its post data. and u need to intercept response.. – Ron Apr 23 '12 at 14:49
  • 1
    Any way to intercept the response? – jul Apr 23 '12 at 14:59
  • 1
    Look at this post http://stackoverflow.com/questions/2376471/how-do-i-get-the-web-page-contents-from-a-webview – Ron Apr 23 '12 at 15:10
  • But u get the data only after its loaded in the webview.. you can hide it in onPageStarted – Ron Apr 23 '12 at 15:13
  • How do you intercept the request and respinses made from within a webpage? Some sites such has gmail do background requests and it is impossible to get this information? – Jono Jun 23 '13 at 09:58
  • This method complained on 4.4 level about network connection on main thread conn.connect(); That line. I have posted my solution below. – Abs Jan 17 '14 at 07:09
  • Came here with the same problem - get response json after post request. Saw accepted+awarded answer which is not answer at all > – mjollneer Mar 07 '22 at 18:22
9

Here is how i achieved this as the method mentioned started to complain about UI thread network connection.

Using ChromeWebView Client and console log the output

    public void OnSignUp_Click(View v) {
    WebView mWebview = new WebView(this);

    mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript

    final Activity activity = this;

    mWebview.setWebChromeClient(new WebChromeClient() {
        public boolean onConsoleMessage(ConsoleMessage cmsg)
        {

                /* process JSON */
            cmsg.message();
            return true;

        }
    });

    mWebview.setWebViewClient(new WebViewClient() {

        public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
            Log.e("Load Signup page", description);
            Toast.makeText(
                    activity,
                    "Problem loading. Make sure internet connection is available.",
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            view.loadUrl("javascript:console.log(document.body.getElementsByTagName('pre')[0].innerHTML);");
        }
    });

    mWebview.loadUrl("https://yourapp.com/json");

}

Hope it helps others.

Abs
  • 3,902
  • 1
  • 31
  • 30
  • 1
    This is by far the easiest solutions and the one that actually worked for me, for catching a redirected SAML JSON response. Additional benefit: Extremely simple and no Networking on UI exception. – AgentKnopf Jun 02 '16 at 08:50
  • It works only if a web page prints messages in a log. It doesn't get POST request. – CoolMind Oct 14 '21 at 16:41
-1

Well, the short answer is that it works quite similar to shouldOverrideUrlLoading(WebView view, String url), as illustrated in the WebView tutorial.

To get you started, see the code below. You simply override the shouldInterceptRequest(WebView view, String url) method of your WebViewClient. Obviously you don't have to do that inline, but for the sake of compactness that's what I did:

Take a look at this.

Community
  • 1
  • 1
pacman
  • 1,061
  • 1
  • 17
  • 36