如何使用HttpClient发布数据?

109

我从Nuget获取了这个 HttpClient。

当我想要获取数据时,我会这样做:

var response = await httpClient.GetAsync(url);
var data = await response.Content.ReadAsStringAsync();

但问题是我不知道如何发布数据?我需要发送一个POST请求并在其中发送这些值:comment="hello world"questionId = 1。这些可以是类的属性,我不知道。

更新 我不知道如何将这些值添加到HttpContent中,因为POST方法需要它。httpClient.Post(string, HttpContent);


你尝试使用过Post方法吗? - Patrick
你应该遵循文档中关于在发送帖子时应该发送哪些内容的说明(如果你正在使用API)。然后,只需填写一个HttpContent并使用PostAsync。你试过了吗? - Patrick
@Patrick谢谢,我已经更新了我的问题。 - user2970840
5
顺便提一下,发帖后10分钟就在评论区加上“有没有人能帮忙?”和一个笑脸可能不会促使其他溢出者更快地帮助你。如果没有人回答你的问题,你可能需要检查一下自己的问题并思考如何改进它,提供更多关于你尝试过什么的信息,而不是期望其他人去猜测你的情况。 - Patrick
@Patrick 好的,我已经更新了。请看看是否足够。 - user2970840
1
如果有人想要使用HttpClient上传文件,请参考以下链接:C# HttpClient 4.5 multipart/form-data upload - RBT
3个回答

221

你需要使用:

await client.PostAsync(uri, content);

类似这样的:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

如果你需要在提交(post)之后获取响应(response),你应该使用:

var stringContent = await response.Content.ReadAsStringAsync();

响应是“无法处理的条目”。也许我在其他地方犯了错误。 - user2970840
18
简化的字典字面量形式如下:var formContent = new FormUrlEncodedContent(new Dictionary<string, string> {{"comment", comment},{"questionId", questionId }});。它创建一个键值对的集合,包括字符串类型的键和值,并将其作为表单数据的编码内容。 - hkarask

8

尝试使用这个:

using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
    using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
    {
        //add parameters on request
        var body = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("test", "test"),
            new KeyValuePair<string, string>("test1", "test1")
        };

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
        client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
        client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
        client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
        //client.DefaultRequestHeaders.Add("Accept", "*/*");

        client.Timeout = TimeSpan.FromMilliseconds(10000);

        var res = await client.PostAsync("", new FormUrlEncodedContent(body));

        if (res.IsSuccessStatusCode)
        {
            var exec = await res.Content.ReadAsStringAsync();
            Console.WriteLine(exec);
        }                    
    }
}

3
根据你的服务器所期望的内容,你可能会想使用MultipartFormDataContent代替FormUrlEncodedContent。 - ed22

-2

使用 UploadStringAsync 方法:

WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
    if (e.Error != null)
    {
        //handle your error here
    }
    else
    {
        //post was successful, so do what you need to do here
    }
};

webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);     

5
谢谢,但我认为这个 HttpClientWebClient 更好。更简单更清晰易懂。不是吗? - user2970840
啊,是的,我太熟悉WebClient了,当我看到这个问题时,脑海中就只有它。我还没有用过HttpClient。对不起! - Lori Lalonde - MSFT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接