如何在 Flutter WebView 中将数据发布到 URL

问题描述 投票:0回答:5

我想将一些数据发布到Flutter WebView中的URL正文中。 那么,我该怎么做呢?

flutter post webview
5个回答
12
投票

webview_flutter
目前没有发送 post 请求的方法。 不过,你可以尝试我的 flutter_inappwebview 插件。它支持POST请求!

使用当前最新版本

5.0.5+3
flutter_inappwebview 插件的一个简单示例是:

var postData = Uint8List.fromList(utf8.encode("firstname=Foo&lastname=Bar"));
controller.postUrl(url: Uri.parse("https://example.com/my-post-endpoint"), postData: postData);

其中

postData
x-www-form-urlencoded
格式的请求正文。

例如,如果您有 PHP 服务器,则可以像平常一样访问

firstname
 和
lastname
值,即
$_POST['firstname']
$_POST['lastname']

您还可以使用初始 POST 请求来初始化

InAppWebView
 小部件,如下所示:

child: InAppWebView(
  initialUrlRequest: URLRequest(
    url: Uri.parse("https://example.com/my-post-endpoint"),
    method: 'POST',
    body: Uint8List.fromList(utf8.encode("firstname=Foo&lastname=Bar")),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  ),
  onWebViewCreated: (controller) {
    
  },
),

6
投票

可以在官方Flutter上运行JS功能WebView ::

1-JS POST 请求示例

**
 * sends a request to the specified url from a form. this will change the window location.
 * @param {string} path the path to send the post request to
 * @param {object} params the parameters to add to the url
 * @param {string} [method=post] the method to use on the form
 */

function post(path, params, method='post') {

  // The rest of this code assumes you are not using a library.
  // It can be made less verbose if you use one.
  const form = document.createElement('form');
  form.method = method;
  form.action = path;

  for (const key in params) {
    if (params.hasOwnProperty(key)) {
      const hiddenField = document.createElement('input');
      hiddenField.type = 'hidden';
      hiddenField.name = key;
      hiddenField.value = params[key];

      form.appendChild(hiddenField);
    }
  }

  document.body.appendChild(form);
  form.submit();
}

2-在 Flutter 中将 JS 函数转换为字符串并调用它

final String postUrl="'https://jsonplaceholder.typicode.com/posts'";
final String postParam= "{name: 'Johnny Bravo'}";
final String requestMethod= "'post'";

final  String jsFunc="function post(path, params, method='post') {"+
    "const form = document.createElement('form');"+
    "form.method = method;"+
    "form.action = path;"+
    "for (const key in params) {"+
    "if (params.hasOwnProperty(key)) {"+
    "const hiddenField = document.createElement('input');"+
    "hiddenField.type = 'hidden';"+
    "hiddenField.name = key;"+
    "hiddenField.value = params[key];"+
    "form.appendChild(hiddenField);}}document.body.appendChild(form);form.submit();}"+
    "post($postUrl, $postParam, method=$requestMethod)";

3-在WebView中运行JS代码

return FutureBuilder<WebViewController>(
    future: _controller.future,
    builder: (BuildContext context,
        AsyncSnapshot<WebViewController> controller) {
      if (controller.hasData) {
        return FloatingActionButton(
          onPressed: () async {
            controller.data!.evaluateJavascript(jsFunc);
          },
          child: const Icon(Icons.call_received),
        );
      }
      return Container();
    });

3
投票

这个问题很久以前就提出了,但我找到了一个新方法

WebView添加新功能)

WebView(
  initialUrl: item.url,
  javascriptMode: JavascriptMode.unrestricted,
  debuggingEnabled: false,
  onWebResourceError: (error) {
    debugPrint(error.domain);
  },
  zoomEnabled: true,
  backgroundColor: Colors.transparent,
  onWebViewCreated: (controller) {
    controller.loadRequest(
      WebViewRequest(
        uri: Uri.parse("YOUR URL"),
        headers: "YOUR MAP<STRING, STRING>",
        method: WebViewRequestMethod.post,
        body: Uint8List.fromList(
          utf8.encode(
            jsonEncode("YOUR MAP<STRING, DYNAMIC>"),
          ),
        ),
      ),
    );
  },
);

0
投票

对我来说这很有效,我找到了一种将表单数据作为正文传递的方法。我使用了flutterhttps://pub.dev/packages/flutter_inappwebview

          url: Uri.parse(POS_URL),
          method: 'POST',
          body: Uint8List.fromList(utf8.encode('input_data=${jsonEncode(jsonPayload)}')),
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
        ),   

0
投票

对我来说,应用了 html 表单自动提交帖子请求,如下

创建一个包含您要自动提交的表单的 HTML 文件。

<!DOCTYPE html>
<html>
<head>
    <title>Auto Submit Form</title>
</head>
<body>
    <form id="myForm" action="https://example.com/submit" method="POST">
        <input type="hidden" name="param1" value="value1">
        <input type="hidden" name="param2" value="value2">
    </form>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('myForm').submit();
        });
    </script>
</body>
</html>

然后您可以使用 flutter_inappwebview 包中的 InAppWebView 小部件将上述 HTML 内容加载到 Flutter WebView 中:

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class WebViewExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    String htmlContent = """
      <!DOCTYPE html>
      <!-- Your HTML content here -->
    """;

    return InAppWebView(
      initialData: InAppWebViewInitialData(data: htmlContent),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.