当前位置:  开发笔记 > 编程语言 > 正文

从C#WinForm将数据POST到PHP页面

如何解决《从C#WinForm将数据POST到PHP页面》经验,为你挑选了1个好方法。

我有一个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) {}

有任何想法吗?我希望它返回我刚刚传递给它的值,以证明我可以从服务器端访问数据.



1> Owen..:

我相信你需要正确编码并发送实际的帖子内容.看起来你只是序列化为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']);

推荐阅读
落单鸟人
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有