我有一个winForms NET3.5SP1应用程序,并希望将数据发布到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代码是:
<?php
echo "hello world";
var_dump($_POST);
?>
返回:
array(0) {}
有什么想法吗?我希望它返回我刚刚传递给它的值,以证明我可以从服务器端访问数据。
答案 0 :(得分:8)
我相信您需要正确编码并发送实际的帖子内容。看起来你只是序列化为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...
这应该在PHP集中获取$_POST
变量。稍后当您切换到JSON时,您可以执行以下操作:
string postData = "json=" + HttpUtility.UrlEncode(serializer.Serialize(p) );
从PHP获取:
$json_array = json_decode($_POST['json']);