使用Flutter向PHP REST API发送HTTP POST请求 [英] HTTP POST request to PHP REST API using Flutter

查看:261
本文介绍了使用Flutter向PHP REST API发送HTTP POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在这方面已经走了太久了,但是我无法弄清楚为什么这不起作用,我想做的就是将一些JSON发布数据发送到我现有的PHP REST API中创建并读取了$_POST["username"]之类的JSON数据,我无法真正更改API的工作方式,因为它可以完美地与另一个应用程序一起使用,因此这与我的抖动代码有关,但是我不确定我今天开始学习它.

So I have been at this for way way too long but I just can't figure out why this isn't working what I'm trying to do is send some JSON post data to an existing PHP REST API that I've created and then read that JSON data like $_POST["username"] and I can't really change how the API works as it's used by another application which it works perfectly with so it's something to do with my flutter code but I'm not sure what as I started learning it today.

我的颤动代码:

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

要使该代码有效,我可以更改哪些代码?
为清楚起见,我确实想处理一个application/json请求,唯一的原因是file_get_contents可以测试PHP API是否实际上在接收数据.

What can I change in my flutter code to make this work?
Just for clarity I do want to handle an application/json request the only reason file_get_contents is there is to test if the PHP API was actually receiving the data.

推荐答案

似乎您应该只发送一个urlencoded表单,而不是对发布数据进行JSON编码.

It looks like you should just be sending a urlencoded form, rather than JSON encoding the post data.

尝试:

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

这篇关于使用Flutter向PHP REST API发送HTTP POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆