c# 没有向 PHP 发送 json 请求 [英] c# is not sending json request to PHP
问题描述
我正在尝试使用 JSON 将数据从 c# 发送到 PHP.
I am attempting to send data from c# to PHP using the JSON.
我在 PHP 页面上看到了NULL".
I see 'NULL' on the PHP page.
这是我的 c# HTTP 请求,它应该将 json 请求发送到 PHP 网页.
Here is my c# HTTP request which should send json request to PHP webpage.
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://localhost/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");
我有 PHPtest.php",其中包含以下代码.
I have PHP "test.php" which has the following code.
<?php
echo json_encode($_POST);
?>
当c#函数运行时;我没有收到任何错误.
When the c# function run; I don't get any errors.
然后我刷新网页并显示NULL"
Then I refresh webpage and it says "NUll"
我想要实现的是 c# 使用 JSON 使用 REST API(HTTP 请求)发送数据.
What I would like to achieve is c# to send data using JSON using REST API (HTTP Request).
然后使用PHP;我将获取数据并保存在 MySql 表中.
Then using PHP; I will get the data and save in MySql Table.
但 PHP 只显示空"
But PHP just shows 'Null'
我做错了什么.
谢谢
编辑
我在 c# 中看到的 DisplayAlert 显示了它传递给 PHP 的字符串.
The DisplayAlert which I see in c# shows the string which it passes to PHP.
PHP 代码
//Receive the RAW post data.
$content = file_get_contents("php://input");
$obj = json_encode($content);
$insert_stmt = $mysqli_scs->prepare("INSERT INTO test (name,address) VALUES (?,?)");
$name =$content->{'name'};
$address = $obj->{'address'};
$insert_stmt->bind_param("ss", $name, $address);
//Execute the statement
$insert_stmt->execute();
推荐答案
你必须看看 C# 调用返回给你什么对吗?
You have to look what C# call returns to you right ?
我不懂 C#,但我不认为 json 必须在 $_POST 变量中发送,而是在请求的正文部分中发送.在香草 PHP 中,您可以通过以下方式获得它:
I don't know C# but I don't think the json must be send in the $_POST variable but in the body part of the request. In vanilla PHP you can get it with :
file_get_contents('php://input');
这篇关于c# 没有向 PHP 发送 json 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!