首页 > 解决方案 > Android 通过 Webview POST 表单数据

问题描述

我的 html 代码中有以下实现。

<!doctype html>
<html ng-app="app">
<head>
<title>post data</title>
</head>
<body>
<div>  
<form action="https://mypaymentgateway/pay" method="post">

<input type="hidden" id="profile_id" name="profile_id" value="123" />
<input type="hidden" id="transaction_id" name="transaction_id" value="abcd" />
<input type="hidden" id="locale" name="locale" value="en" />
<input type="submit" id="btnsubmit" value="Confirm" /> 

</form>
</div>

</body>
</html>

我想要做的是通过调用我的付款网址(“https://mypaymentgateway/pay”)的 POST 方法在 webview 中提交上述值,而无需点击“确认”按钮。我已经在这里这里以及其他来源尝试过解决方案。但似乎没有任何工作正常。请帮我解决这个问题。

标签: javaandroidpostandroid-webviewform-data

解决方案


form.submit()如果您想在不按下按钮的情况下发布表单,请尝试自行调用

根据您的需要,有两种方法可以做到这一点,通过 HTML 文件本身的 JavaScript 或通过启用 WebView 组件的 Java 文件。

通过 HTML 文件中的 JavaScript:

<form id="myForm" action="https://mypaymentgateway/pay" method="POST"> ... </form>
<script>
function submitMyForm() {
    var myForm = document.querySelector("#myForm");
    myForm.submit();
}
</script>

您只需submitMyForm()在需要的地方调用 JavaScript。

通过 Java 文件(在 HTML 文件中的 JavaScript 的全局范围内定义前面的函数):

//First enable your JavaScript
webView.getSettings().setJavaScriptEnabled(true);

//And then with a loadURL you can trick the WebView into executing Javascript
webView.loadUrl("javascript:submitMyForm");

归功于:Android 在 WebView 中调用 JavaScript 函数


推荐阅读