2

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();
        }
    }

インターネット全体を調べましたが、httppostメソッドの実行方法を示す実用的な例やドキュメントは見つかりませんでした。どんな材料やサンプルでも私は大いに役立ちます。

4

2 に答える 2

1

MultipartFormDataContentの代わりにFormUrlEncodedContentを試してください。

var content = new FormUrlEncodedContent(
    new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("track", "Beautiful"),
        new KeyValuePair<string, string>("artist", "Enimem")
    }
);
于 2012-04-27T18:50:18.137 に答える
1

POSTデータをリクエストコンテンツの本文に設定する場合は、次の方法を使用することをお勧めします。デバッグする必要がはるかに簡単です!

投稿先のURLを使用してHttpClientオブジェクトを作成します。

string oauthUrl = "https://accounts.google.com/o/oauth2/token";
HttpClient theAuthClient = new HttpClient();

Postメソッドを使用してURLにリクエストを作成します

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
    }
}
于 2012-11-20T16:51:48.230 に答える