![](/img/trans.png)
[英]How can i make an HTTP POST request and and use the Json Response i should get in android
[英]How can I get the JSON response of a POST request in a WebView?
我有一個帶有 html 的WebView
,其中包含一個表單(post)。 單擊某個提交按鈕時,我會收到 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;
}
});
謝謝
您應該覆蓋WebViewClient
的shouldOverrideUrlLoading
方法
@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 獲取網頁內容?
這是我如何實現這一點,因為提到的方法開始抱怨 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");
}
希望它可以幫助其他人。
嗯,簡而言之,它的工作方式與 shouldOverrideUrlLoading(WebView view, String url) 非常相似,如 WebView 教程中所示。
要開始使用,請參閱下面的代碼。 您只需覆蓋 WebViewClient 的 shouldInterceptRequest(WebView view, String url) 方法。 顯然,您不必內聯,但為了緊湊起見,我就是這樣做的:
看看這個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.