如何使用 HttpClient 发布数据?

我有来自 Nuget 的 abc 0 httpClient。

当我想要得到数据时,我这样做:

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

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

更新 我不知道如何将这些值添加到 HttpContent,因为 post 方法需要它

165800 次浏览

You need to use:

await client.PostAsync(uri, content);

Something like that:

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

And if you need to get the response after post, you should use:

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

Hope it helps ;)

Use UploadStringAsync method:

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

Try to use this:

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