Santo Shakil
Santo Shakil

Reputation: 1052

How to Post Data to URL in Flutter WebView

I want to post some data to the URL body in Flutter WebView. So, how can I do it?

Upvotes: 8

Views: 18924

Answers (6)

Noyon
Noyon

Reputation: 107

I tried all of above approach. Nothing help me to solve my problem. I have been trying to implement Barclaycard payment gateway integration. i just add this line and solve my problem using InAppWebView

Uint8List.fromList(utf8.encode(payLoad.replaceAll(" ", "+")))

here payload is string like

payload="param1=data1&parma2=data&...."

This is my full implementation

body: InAppWebView(
    initialUrlRequest: URLRequest(
        url: Uri.parse(
            "https://payments.epdq.co.uk/ncol/prod/orderstandard.asp"),
        method: 'POST',
        body: Uint8List.fromList(utf8.encode(payLoad.replaceAll(" ", "+"))),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'})

Upvotes: 0

Javeed Ishaq
Javeed Ishaq

Reputation: 7105

for me applied html form auto submission post request as below

Create an HTML file that contains the form you want to submit automatically.

and then You can load the HTML content into a Flutter WebView using the InAppWebView widget from the flutter_inappwebview package:

    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>
<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>
        """;
    
        return InAppWebView(
          initialData: InAppWebViewInitialData(data: htmlContent),
        );
      }
    }

Upvotes: 0

ANUSREE P
ANUSREE P

Reputation: 141

For me this worked ,I found a way to pass form data as body .I have used flutter https://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',
          },
        ),   

Upvotes: 2

Kirill_Z
Kirill_Z

Reputation: 306

the question was created a long time ago, but I found a new way

In WebView add new function)

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>"),
          ),
        ),
      ),
    );
  },
);

Upvotes: 4

Milad Ahmadi
Milad Ahmadi

Reputation: 1097

You can run JS functions on official Flutter WebView ::

1-Example of Post request by JS

**
 * 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-Convert JS function to a String in Flutter and Call that

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- Run JS code in WebView

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();
    });

Upvotes: 7

Lorenzo Pichilli
Lorenzo Pichilli

Reputation: 3429

webview_flutter doesn't have a method to send post requests at this moment. However, you can try my flutter_inappwebview plugin. It supports POST requests!

A simple example using the current latest version 5.0.5+3 of the flutter_inappwebview plugin is:

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

where the postData is the Body of the request in x-www-form-urlencoded format.

For example, if you have a PHP server, you can access the firstname and lastname values as you normally would do, that is $_POST['firstname'] and $_POST['lastname'].

You can also initialize the InAppWebView widget with an initial POST request like this:

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) {
    
  },
),

Upvotes: 15

Related Questions