使用Flutter向PHP REST API发送HTTP POST请求

编程入门 行业动态 更新时间:2024-10-18 21:17:48
本文介绍了使用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( '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请求

本文发布于:2023-11-26 20:48:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635141.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:REST   PHP   Flutter   POST   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!