Windows Phone 8中的Post方法

时间:2014-04-21 22:31:07

标签: c# windows-phone-8 http-post

我需要在WP8应用程序中使用post方法向php服务器发送一些参数,并以json格式获取响应。我已经尝试过在stackoverflow和其他网站上找到的所有东西,但仍然没有。

我提出的最后一个代码是:

public static async void GetData(string url, string data)
{
    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.PostAsync(new Uri(url), new StringContent(data));

    response.EnsureSuccessStatusCode();
    string responseBody = await response.Content.ReadAsStringAsync();
    MessageBox.Show(responseBody); // just showing the response for now
}

它显示来自服务器的消息(这是一个错误,说明某些字段丢失),它实际上与服务器通信但问题在于发送数据。我将上述方法称为:

GetData("http_address_here", "?action=REGISTER&email=asc@fsdf.com&password=54561wefwe&firstname=sdfsdf&lastname=sdfsdf&picture=10");

但是我看到了一个用xml发送数据的例子。可能错误在于调用方法。看过几十个示例代码并尝试一切,我真的很困惑。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:2)

我终于设法解决了这个问题。谢谢大家的帮助。下面是工作代码,它使用POST方法,生成的json对象存储为字符串。

var values = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("email", "qewfwef"),
                    new KeyValuePair<string, string>("password", "qewfwef"),
                    new KeyValuePair<string, string>("firstname", "qewfwef"),
                    new KeyValuePair<string, string>("lastname", "qewfwef"),
                    new KeyValuePair<string, string>("picture", "123456")
                };

        var httpClient = new HttpClient(new HttpClientHandler());
        HttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(values));
        response.EnsureSuccessStatusCode();
        var responseString = await response.Content.ReadAsStringAsync();

        MessageBox.Show(responseString.ToString()); // just to see what we get

答案 1 :(得分:1)

你能试试吗

public static async Task<string> SendRequestPostResponse()
    {
        try
        {
            var postRequest = (HttpWebRequest)WebRequest.Create("your Url Here");

            postRequest.ContentType = "application/x-www-form-urlencoded"; // Whichever content type you want to POST
            postRequest.Method = "POST";

            using (var requestStream = await postRequest.GetRequestStreamAsync())
            {
                byte[] postDataArray = Encoding.UTF8.GetBytes("your data here"); // Data for the POST request here
                await requestStream.WriteAsync(postDataArray, 0, postDataArray.Length);
            }

            WebResponse postResponse = await postRequest.GetResponseAsync();

            if (postResponse != null)
            {
                var postResponseStream = postResponse.GetResponseStream();
                var postStreamReader = new StreamReader(postResponseStream);

                string response = await postStreamReader.ReadToEndAsync();

                return response;
            }
            return null;
        }
}

答案 2 :(得分:0)

HTTPWebRequest将是另一种选择。