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 do
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.
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?
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.