Sumodh S
Sumodh S

Reputation: 741

JSON call from C# to php

I am trying to call a PHP file from my c# code. This is my 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("http://localhost") 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();
                    }
                }

                MessageBox.Show(json1);

My problem is that the c# method is not sending my object and my php code is

<?php    
     echo  json_encode($_POST);
?>

please help

Upvotes: 0

Views: 3850

Answers (2)

MrCode
MrCode

Reputation: 64536

The problem is your C# is sending raw POST data and the PHP $_POST array only works with URL encoded key/value pairs.

On the PHP side, retrieve the raw POST data, bypassing the $_POST array. Also it makes no sense to JSON encode the data on the PHP side, because it is already JSON. Use json_decode() for the reverse operation.

echo file_get_contents("php://input");

Upvotes: 0

user3036342
user3036342

Reputation: 1045

$_POST doesn't understand json as per my comment pointing to the solution elsewhere on SO (Google makes life easier)

Here is the recommended code to use:

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Upvotes: 1

Related Questions