POST data to a PHP page from C # WinForm

I have a winForms NET3.5SP1 application and you want the POST data to be on a PHP page.

I am also going to pass it as JSON, but first wanted to get a direct POST.

Here is the code:

Person p = new Person(); p.firstName = "Bill"; p.lastName = "Gates"; p.email = " asdf@hotmail.com "; p.deviceUUID = "abcdefghijklmnopqrstuvwxyz"; JavaScriptSerializer serializer = new JavaScriptSerializer(); string s; s = serializer.Serialize(p); textBox3.Text = s; // s = "{\"firstName\":\"Bill\",\"lastName\":\"Gates\",\"email\":\" asdf@hotmail.com \",\"deviceUUID\":\"abcdefghijklmnopqrstuvwxyz\"}" HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.davemateer.com/ig/genius/newuser.php"); //WebRequest request = WebRequest.Create("http://www.davemateer.com/ig/genius/newuser.php"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; //byte[] byteArray = Encoding.UTF8.GetBytes(s); 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(); textBox4.Text = (((HttpWebResponse)response).StatusDescription); dataStream = response.GetResponseStream (); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd (); textBox4.Text += responseFromServer; reader.Close (); dataStream.Close (); response.Close (); 

And the PHP5.2 code:

 <?php echo "hello world"; var_dump($_POST); ?> 

this is returning:

 array(0) {} 

Any ideas? I want it to return the values ​​that I just passed in order to prove that I can access the data from the server side.

+4
source share
1 answer

I believe that you need to properly encode and send the actual content. it looks like you are just serializing in JSON, which PHP doesn't know what to do (i.e. it will not set it as $_POST values)

 string postData = "firstName=" + HttpUtility.UrlEncode(p.firstName) + "&lastName=" + HttpUtility.UrlEncode(p.lastName) + "&email=" + HttpUtility.UrlEncode(p.email) + "&deviceUUID=" + HttpUtility.UrlEncode(p.deviceUUID); byte[] byteArray = Encoding.ASCII.GetBytes(postData); // etc... 

this should get your $_POST variable in the PHP set. later when you switch to JSON you can do something like:

 string postData = "json=" + HttpUtility.UrlEncode(serializer.Serialize(p) ); 

and grab PHP:

 $json_array = json_decode($_POST['json']); 
+8
source

All Articles