【发布时间】:2019-03-06 11:49:51
【问题描述】:
我已经问过这个问题,但需要进一步的帮助。 c# is not sending json request to PHP
我正在尝试使用 JSON 和 REST API HTTP 请求将数据从 c# 发送到 PHP 网页。
在 PHP 页面上我看到“字符串 (0)”
c#代码
user user = new user();
{
user.firstname = "aaaa";
user.secondname = "aaaaaaaaaaa";
user.email = "aaa";
user.phonenumber = "aaa";
};
string json = JsonConvert.SerializeObject(user);
HttpWebRequest request = WebRequest.Create("https://scs.agsigns.co.uk/test.php") as HttpWebRequest;
request.ContentType = "application/json";
//request.Accept = "application/json, text/javascript, */*";
request.Method = "POST";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(json);
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();
string json1 = "";
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
json1 += reader.ReadLine();
}
}
DisplayAlert("Alert", json1, "OK");
PHP
$content = file_get_contents("php://input");
var_dump($content);
在 c# 中我收到此警报
在 PHP 网页中,我看到以下内容
我想获取应用程序发送并保存到 MySql 的数据。
编辑
我已修改 PHP 文件代码以在 MySQL 中保存数据。
我遇到错误
注意:尝试在第 16 行的 C:\inetpub\scs\test.php 中获取非对象的属性“名称”
这是我的 PHP 代码。
//Receive the RAW post data.
$content = file_get_contents("php://input");
$obj = json_encode($content);
$insert_stmt = $mysqli->prepare("INSERT INTO test (name,address) VALUES (?,?)");
$name =$obj->{'name'};
$address = $obj->{'address'};
$insert_stmt->bind_param("ss", $name, $address);
//Execute the statement
$insert_stmt->execute();
【问题讨论】:
-
如果您重新加载页面,页面将始终显示为空,因为在页面重新加载时尚未发送任何内容。要查看它是否正常工作,请返回响应
exit(json_encode(['success' => true]));并在您的 C# 中选择它。 -
所以当app向PHP发送数据时;我如何在 PHP 中使用该数据,因为我想将该数据保存在 MySQL 中
-
当app发出请求时,如果一切正常,那么你可以在PHP中使用它。因此,只需编写 PHP 代码的其余部分,就好像数据已达到正常水平并测试行是否出现在 db 中。