duanhong1985 2019-03-06 09:58
浏览 68
已采纳

c#没有向PHP发送json请求

I am attempting to send data from c# to PHP using the JSON.

I see 'NULL' on the PHP page.

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");

I have PHP "test.php" which has the following code.

<?php

echo json_encode($_POST);


?>

When the c# function run; I don't get any errors.

Then I refresh webpage and it says "NUll"

What I would like to achieve is c# to send data using JSON using REST API (HTTP Request).

Then using PHP; I will get the data and save in MySql Table.

But PHP just shows 'Null'

What I am doing wrong.

Thank you

EDIT

The DisplayAlert which I see in c# shows the string which it passes to PHP.

c# alert of string which it passes to PHP

PHP webpage shows string (0)

PHP Code

//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();
  • 写回答

1条回答 默认 最新

  • dongying6659 2019-03-06 10:04
    关注

    You have to look what C# call returns to you right ?

    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');

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab