【问题标题】:HTTP POST request to PHP REST API using Flutter使用 Flutter 对 PHP REST API 的 HTTP POST 请求
【发布时间】:2020-08-27 15:52:24
【问题描述】:

所以我在这方面已经太久了,但我只是不明白为什么这不起作用我正在尝试做的是将一些 JSON 发布数据发送到我现有的 PHP REST API'我已经创建并读取了像 $_POST["username"] 这样的 JSON 数据,我无法真正改变 API 的工作方式,因为它被另一个应用程序使用,它可以完美地工作,所以这与我的颤振代码有关,但我不确定是什么因为我今天开始学习它。

我的颤振代码:

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

http.Response response = await http.post(
    'https://path.to.php.file',
    headers: <String, String>{
      'Content-Type': 'application/json',
    },
    body: jsonEncode(<String, String>{
      "formname": "login",
      "username": globals.currentUsername, // value = futurelucas4502
      "password": globals.currentPassword, // value = password
      "datetime": DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now()) // MySql Datetime format
    }),
  );

  debugPrint("Response: " + response.body);
  debugPrint("Status: " + (response.statusCode).toString());

减少 PHP 代码:

<?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    echo file_get_contents('php://input');
    echo '<br>';
    echo $_POST["username"];
?>

输出:

Response: {"formname":"login","username":"futurelucas4502","password":"password","datetime":"2020-05-12 00:01:33"}<br><br />

<b>Notice</b>:  Undefined index: username in <b>/storage/ssd2/545/12156545/public_html/temp/index.php</b> on line <b>7</b><br />

Status: 200

我可以在我的颤振代码中进行哪些更改以使其正常工作?
编辑:为了清楚起见,我确实想处理应用程序/json 请求,file_get_contents 的唯一原因是测试 PHP API 是否实际接收数据。

【问题讨论】:

  • 你不能只在你的 php 脚本中获取用户名值,对吗?
  • PHP 代码相当混乱。您要处理application/json 请求还是application/x-www-form-urlencodedfile_get_contents('php://input') 建议前者,但$_POST["username"] 建议后者。你不能两者兼得。这个其他应用程序使用什么?
  • 我想使用 application/json 和 $_POST["username"] 但谢谢我现在有一个解决方案

标签: php flutter


【解决方案1】:

看起来您应该只是发送一个 urlencoded 表单,而不是对 post 数据进行 JSON 编码。

试试:

body: <String, String>{
  "formname": "login",
  "username": globals.currentUsername, // value = futurelucas4502
  "password": globals.currentPassword, // value = password
  "datetime": DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now()) // MySql Datetime format
},

【讨论】:

  • 导致Exception has occurred. StateError (Bad state: Cannot set the body fields of a Request with content-type "application/json".)
  • 因此,删除该标头,这是有道理的,因为您没有发送 JSON,因此不应该设置内容类型。
猜你喜欢
  • 2016-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
相关资源
最近更新 更多