3

我正在尝试创建一个 POST 请求,但我无法让它工作。

这是请求的格式,它有 3 个参数,accountidentifier / type / seriesid

http://someSite.com/api/User_Favorites.php?accountid=accountidentifier&type=type&seriesid=seriesid

这是我的 C#

using (var httpClient = new HttpClient())
        {
            httpClient.BaseAddress = new Uri("http://somesite.com");
            var content = new FormUrlEncodedContent(new[] 
            {
                new KeyValuePair<string, string>("accountidentifier", accountID),
                new KeyValuePair<string, string>("type", "add"),
                new KeyValuePair<string, string>("seriesid", seriesId),

            });

            httpClient.PostAsync("/api/User_Favorites.php", content);
}

有任何想法吗?

4

2 回答 2

3

IMO,C# 中的字典对于此类任务非常有用。下面是一个完成精彩 POST 请求的异步方法示例:

public class YourFavoriteClassOfAllTime {

    //HttpClient should be instancied once and not be disposed 
    private static readonly HttpClient client = new HttpClient();

    public async void Post()
    {

        var values = new Dictionary<string, string>
        {  
            { "accountidentifier", "Data you want to send at account field" },
            { "type", "Data you want to send at type field"},
            { "seriesid", "The data you went to send at seriesid field"
            }
        };

        //form "postable object" if that makes any sense
        var content = new FormUrlEncodedContent(values);

        //POST the object to the specified URI 
        var response = await client.PostAsync("http://127.0.0.1/api/User_Favorites.php", content);

        //Read back the answer from server
        var responseString = await response.Content.ReadAsStringAsync();
    }
}
于 2019-02-25T06:34:20.583 回答
-2

你也可以试试 WebClient。它试图准确地模拟浏览器会做什么:

            var uri = new Uri("http://whatever/");
            WebClient client = new WebClient();
            var collection = new Dictionary<string, string>();
            collection.Add("accountID", accountID );
            collection.Add("someKey", "someValue");
            var s = client.UploadValuesAsync(uri, collection);

UploadValuesAsync 在哪里发布您的收藏。

于 2013-07-24T23:07:31.127 回答