【问题标题】:How to send POST request from Flutter app to PHP server如何将 POST 请求从 Flutter 应用程序发送到 PHP 服务器
【发布时间】:2021-05-10 22:24:22
【问题描述】:

我尝试从我的 Dart 应用程序向我的服务器上的 PHP 文件发送一个 POST 请求,该文件只检查是否设置了 $_POST['username'],发生的情况是请求似乎到达了服务器,但是服务器拒绝“读取”:

这是服务器在收到请求时看到的(通过使用:file_get_contents('php://input'))

{"username":"testUsername"}

但如果我尝试做类似的事情:

isset($_POST['username']) 

这总是返回 false。

这是我用来发送 POST 请求的方法:

  import 'dart:convert';
  import 'package:http/http.dart' as http;

  final String url = "my.domain.com";
  final String unencodedPath = "/subfolder/myfile.php";
  final Map<String, String> headers = {'Content-Type': 'application/json; charset=UTF-8'};
  final Map<String,String> body = {'username': 'testUsername'};
    
    Future<http.Response> makePostRequest(String url, String unencodedPath , Map<String, String> header, Map<String,String> requestBody) async {
      final response = await http.post(
        Uri.http(url,unencodedPath),
        headers: header,
        body: jsonEncode(requestBody),
      );
      print(response.statusCode);
      print(response.body);
    }

    makePostRequest(url, unencodedPath, headers, body);

为什么 isset($_POST['username']) 看不到我的 POST 发送值?

【问题讨论】:

    标签: php flutter dart


    【解决方案1】:

    你从 Flutter 端的 post 请求是正确的

    isset($_POST['username']) 
    

    将返回 null,因为用户名是 json 对象的一部分,如果:

    username = {"username":"testUsername"}
    

    您的请求满足上述格式。

    要检查数据,您可以:

     if(!isset($_POST)){
            // Takes raw data from the request
            $json = file_get_contents('php://input');
    
    // Converts it into a PHP object
            $data = json_decode($json);
          //add your check here that is $data["username"] as bellow
            isset($data["username"])
        }
    

    您还可以使用其他方法检查有效的 json。

    【讨论】:

    • 是的,我只是删除了 body: jsonEncode(requestBody) 中的 jsonEncode,一切正常.. ty
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2021-12-25
    • 2014-02-19
    • 2020-03-24
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多