Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How do I post a json string from c# windows application to a php page?

I am using the following code but it returns null string from php page?

string Uname, pwd, postData, postData1;
            Uname = txtUname.EditValue.ToString();
            pwd = txtPassword.EditValue.ToString();

            List<request1> JSlist = new List<request1>();
            request1 obj = new request1();
            obj.emailid = Uname;
            obj.password = pwd;
            JSlist.Add(obj);

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string s;
            s = serializer.Serialize(obj);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://lab.amusedcloud.com/test/login_action.php");

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] byteArray = Encoding.ASCII.GetBytes(s);
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();
            MessageBox.Show(((HttpWebResponse)response).StatusDescription);
            dataStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            MessageBox.Show(responseFromServer);

            reader.Close();
            dataStream.Close();
            response.Close();

PHP

<?php
$json_array = json_decode($_POST['json']);

?>

connection established successfully but this php page returns array(0){}

share|improve this question
 
What are you expecting the PHP page to return? Currently that code doesn't output anything. –  David Jun 29 at 12:03
 
Have you tried to examine the traffic using developer tools of chrome or fiddler and see where the problem is? –  saamorim Jun 29 at 12:09
add comment

1 Answer

Based on the ContentType property, it looks like you should be form encoding the content your sending to the PHP script. If thats the case you need to make sure the content you are sending is in key/value format:

[key]=[value]

In your case it looks like the PHP script is expecting a parameter with the key "json", so the data your sending would be something like:

"json=" & s 

Hope that helps.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.