duancaishi1897
duancaishi1897
2019-03-06 11:49

在通过c#RESI API传递Json之后,PHP网页显示空字符串

已采纳

I have already asked this question but need further help. c# is not sending json request to PHP

I am trying to send data from c# to PHP webpage using the JSON & REST API HTTP request.

On PHP page I see "String (0)"

c# Code

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

In c# I get this alert

c# display alert message

In the PHP webpage, I see following

PHP page shows string(0)

What I want to get data which app sendand save into MySql.

EDIT

I have ammended the PHP file code to save data in MySQL.

I am getting error

Notice: Trying to get property 'name' of non-object in C:\inetpub\scs\test.php on line 16

This is my PHP code.

//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();
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douhuang3740 douhuang3740 2年前

    You should use HttpClient instead of HttpWebRequest

    Your request would look like this with HttpClient

    public async void SendUserDataToServer()
    {
        user user = new user();
        {
            user.firstname = "aaaa";
            user.secondname = "aaaaaaaaaaa";
            user.email = "aaa";
            user.phonenumber = "aaa";
        };
        string json = JsonConvert.SerializeObject(user);
        using (var client = new HttpClient())
        {
            var response = await client.PostAsync(
                "https://scs.agsigns.co.uk/test.php", 
                 new StringContent(json, Encoding.UTF8, "application/json"));
        }
        DisplayAlert("Alert", json, "OK");
    }
    

    Reference: this

    点赞 评论 复制链接分享