如何在windows 8 metro中执行post方法?

时间:2012-04-25 09:38:59

标签: http-post windows-8 microsoft-metro

我已经关注了HttpClient示例,但无法弄清楚如何使用2个参数发布方法。

以下是我尝试的但它返回错误的网关错误:

        private async void Scenario3Start_Click(object sender, RoutedEventArgs e)
    {
        if (!TryUpdateBaseAddress())
        {
            return;
        }

        Scenario3Reset();
        Scenario3OutputText.Text += "In progress";

       string resourceAddress =  "http://music.api.com/api/search_tracks";
        try
        {
            MultipartFormDataContent form = new MultipartFormDataContent();
        //    form.Add(new StringContent(Scenario3PostText.Text), "data");
            form.Add(new StringContent("Beautiful"), "track");
            form.Add(new StringContent("Enimem"), "artist");

            HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, form);
        }
        catch (HttpRequestException hre)
        {
            Scenario3OutputText.Text = hre.ToString();
        }
        catch (Exception ex)
        {
            // For debugging
            Scenario3OutputText.Text = ex.ToString();
        }
    }

我查看了整个互联网,但找不到任何显示如何执行http post方法的工作示例或文档。任何材料或样品都会对我有所帮助。

2 个答案:

答案 0 :(得分:1)

尝试FormUrlEncodedContent而不是MultipartFormDataContent:

var content = new FormUrlEncodedContent(
    new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("track", "Beautiful"),
        new KeyValuePair<string, string>("artist", "Enimem")
    }
);

答案 1 :(得分:1)

我更倾向于采用以下方法将POST数据设置为请求内容主体。必须调试它更容易!

使用您要发布到的网址

创建您的HttpClient对象
string oauthUrl = "https://accounts.google.com/o/oauth2/token";
HttpClient theAuthClient = new HttpClient();

使用Post方法将您的请求构建到您的网址

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, oauthUrl); 

创建一个内容字符串,其参数以POST数据格式显式设置,并在请求中设置:

string content = "track=beautiful" +
  "&artist=eminem"+
  "&rating=explicit";

request.Method = HttpMethod.Post;
request.Content = new StreamContent(new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)));
request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

发送请求并获得回复:

try
{                
    HttpResponseMessage response = await theAuthClient.SendAsync(request);
    handleResponse(response);
}
catch (HttpRequestException hre)
{

}            

一旦请求返回,您的处理程序将被调用,并且将有来自POST的响应数据。下面的示例显示了一个处理程序,您可以将断点放入以查看响应内容是什么,此时,您可以解析它或执行您需要执行的操作。

public async void handleResponse(HttpResponseMessage response)
{
    string content = await response.Content.ReadAsStringAsync();

    if (content != null)
    {
        // put your breakpoint here and poke around in the data
    }
}