jul*_*jul 14 post android json android-webview
我有一个WebView包含表格的html(帖子).单击某个提交按钮时,我会收到JSON响应.
我怎样才能获得这个JSON?
如果我不拦截请求,json会显示在webview上,所以我想我应该使用shouldInterceptRequest(我使用的是API 12),但我不知道如何获取json.
或者也许有更好的方法,比如拦截响应而不是请求?
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;
}
});
Run Code Online (Sandbox Code Playgroud)
谢谢
Abs*_*Abs 10
以下是我如何实现这一点,因为提到的方法开始抱怨UI线程网络连接.
使用ChromeWebView客户端和控制台记录输出
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");
}
Run Code Online (Sandbox Code Playgroud)
希望它能帮助别人.
你应该覆盖的shouldOverrideUrlLoading方法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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29995 次 |
| 最近记录: |