我有一个winForms NET3.5SP1应用程序,并希望将数据POST到PHP页面.
我也将把它作为JSON传递,但是希望直接在POST工作.
这是代码:
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 ();
PHP5.2代码是:
返回:
array(0) {}
有任何想法吗?我希望它返回我刚刚传递给它的值,以证明我可以从服务器端访问数据.
我相信你需要正确编码并发送实际的帖子内容.看起来你只是序列化为JSON,PHP不知道该怎么做(即,它不会将其设置为$_POST
值)
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...
这应该$_POST
在PHP集中得到你的变量.稍后当你切换到JSON时,你可以做类似的事情:
string postData = "json=" + HttpUtility.UrlEncode(serializer.Serialize(p) );
并从PHP抓取:
$json_array = json_decode($_POST['json']);