在Windows Phone 8中发布Http post

时间:2013-11-30 10:50:26

标签: windows-phone-8 http-post

我是Windows Phone 8开发的新手。

您能帮我解决一下如何通过Windows Phone 8中的http post电话将xml数据发送到服务器吗?

由于

1 个答案:

答案 0 :(得分:0)

这是我在项目中使用的示例代码。根据您的需要进行修改

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url to submit to");
req.Method = "POST";

//Add a Header something like this
//req.Headers["SOAPAction"] = "http://asp.net/ApplicationServices/v200/AuthenticationService/Login";

req.ContentType = "text/xml; charset=utf-8";

//req.UserAgent = "PHP-SOAP/5.2.6";

string xmlData = @"<?xml version=""1.0"" encoding=""UTF-8""?>Your xml data";

// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(xmlData);
req.Headers[HttpRequestHeader.ContentLength] = byteArray.Length.ToString();

req.BeginGetRequestStream(ar =>
{
    using (var requestStream = req.EndGetRequestStream(ar))
    {
        // Write the body of your request here
        requestStream.Write(byteArray, 0, xmlData.Length);
    }

    req.BeginGetResponse(a =>
    {
        try
        {
            var response = req.EndGetResponse(a);
            var responseStream = response.GetResponseStream();

            using (var streamRead = new StreamReader(responseStream))
            {
                // Parse the response message here
                string responseString = streamRead.ReadToEnd();
                //If response is also XML document, parse it like this
                XDocument xdoc = XDocument.Parse(responseString);
                string result = xdoc.Root.Value;

                if (result == "true")
                {
                    //Do something here
                }
                else
                    Dispatcher.BeginInvoke(() =>
                    {
                        //result failed
                        MessageBox.Show("Some error msg");
                    });
            }
        }
        catch (Exception ex)
        {
            Dispatcher.BeginInvoke(() =>
            {
                //if any unexpected exception occurs, show the exception message
                MessageBox.Show(ex.Message);
            });
        }

    }, null);

}, null);