如何使用HttpClient发布数据?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用HttpClient发布数据?相关的知识,希望对你有一定的参考价值。
我有来自Nuget的this HttpClient。
当我想获取数据时,我这样做:
var response = await httpClient.GetAsync(url);
var data = await response.Content.ReadAsStringAsync();
但问题是我不知道如何发布数据?我必须发送一个帖子请求并在其中发送这些值:comment="hello world"
和questionId = 1
。这些可以是一个类的属性,我不知道。
更新我不知道如何将这些值添加到HttpContent
,因为post方法需要它。 httClient.Post(string, HttpContent);
答案
你需要使用:
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);
如果您需要在发布后获得响应,您应该使用:
var stringContent = await response.Content.ReadAsStringAsync();
希望能帮助到你 ;)
另一答案
试着用这个:
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);
}
}
}
另一答案
使用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);
以上是关于如何使用HttpClient发布数据?的主要内容,如果未能解决你的问题,请参考以下文章