C# HttpClient POST 请求

标签 c# http http-post

我正在尝试创建一个 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);
}

有任何想法吗?

最佳答案

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

关于C# HttpClient POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17846026/

相关文章:

java - Android:AndroidHttpClient - 如何设置超时?

perl - 如何使用 LWP 发出 JSON POST 请求?

security - HTTP POST 容易改变吗?

c# - 用于实时应用程序的异步与同步套接字服务器

c# - LINQ to Entities 无法识别方法 'System.String GetMonthName(Int32)' 方法

c# - 无法将 php 正则表达式转换为 C# 正则表达式

C++ REST SDK 如何检查http地址是否无效

python - 通过 Http 将视频文件从 Unity 上传到 Python

java - 异步post方法中设置连接超时的方法

c# - 部分 View 提交