tags:

views:

2901

answers:

3

I have a winForms NET3.5SP1 app, and want to POST data to a PHP page.

I'm also going to be passing it as JSON, but wanted to get straight POST working first.

Here is the code:

    Person p = new Person();
    p.firstName = "Bill";
    p.lastName = "Gates";
    p.email = "[email protected]";
    p.deviceUUID = "abcdefghijklmnopqrstuvwxyz";

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    string s;
    s = serializer.Serialize(p);
    textBox3.Text = s;
    // s = "{\"firstName\":\"Bill\",\"lastName\":\"Gates\",\"email\":\"[email protected]\",\"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 is:

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

this returns back:

array(0) {}

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

Cheers!

+4  A: 

i believe you need to properly encode and send the actual post content. it looks like you're just serializing into JSON, which PHP doesn't know what to do with (ie, it won't 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 PHP set. later when you switch to JSON you could do something like:

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

and grab from PHP:

$json_array = json_decode($_POST['json']);
Owen
Thanks a lot man. Was about to ask this exact question!
Irwin
A: 

Many thanks Owen, works like a charm!

Cheers

nzs

Dave
A: 

Many thanks Owen... genious u r... God Bless You

booota