如何将Windows Phone 8应用程序数据发送到服务器

时间:2014-02-27 06:00:16

标签: windows-phone-8 windows-phone

我的反馈表单中只有两个输入参数,电子邮件,反馈和仅提交按钮。 我想将此数据发送(POST)到http://questoons.com/data.php

等特定网址

那么如何将windows phone 8 app中的数据发布到特定的URL?

任何代码示例或网络链接都将受到高度赞赏。

2 个答案:

答案 0 :(得分:2)

我建议编写一个特定的类来处理POST。

public class PostRequestParameters
    {
        public List<PostRequestParameterObject> prms;

        public PostRequestParameters()
        {
            prms = new List<PostRequestParameterObject>();
        }

        public void AddPair(string id, string val)
        {
            prms.Add(new PostRequestParameterObject(id, val));
        }

        public String FormPostData()
        {
            StringBuilder buffer = new StringBuilder();

            for (int i = 0; i < prms.Count; i++)
            {
                if (i == 0)
                {
                    buffer.Append(System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
                }
                else
                {
                    buffer.Append("&" + System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
                }
            }

            return buffer.ToString();
        }
    }

    public class PostRequestParameterObject
    {
        public string id;
        public string value;

        public PostRequestParameterObject(string id, string val)
        {
            this.id = id;
            this.value = val;
        }
    }

然后你可以用它来发送POST数据:

private void buttonSend_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {               
                WebClient wc = new WebClient();
                wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
                wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
                wc.Encoding = Encoding.UTF8;

                PostRequestParameters prms = new PostRequestParameters();
                prms.AddPair("par1", textBox1.Text);
                prms.AddPair("par2", textBox2.Text);
                prms.AddPair("par3", GetMPar3());

                wc.UploadStringAsync(new Uri(url), "POST", prms.FormPostData(), null);

        }

        // you can parse response here
        private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            // do something
        }

答案 1 :(得分:1)

您可以尝试使用WebClientUploadStringAsync()功能:

string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";

var wc = new WebClient();
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.UploadStringAsync(new Uri(URI, UriKind.Absolute), myParameters);

[For Reference]