如何使用HttpClient的发布数据? [英] How to post data using HttpClient?
问题描述
我有这 HttpClient的距离的NuGet。
I have got this HttpClient from Nuget.
当我想要得到的数据我做这种方式:
When I want to get data I do it this way:
var response = await httpClient.GetAsync(url);
var data = await response.Content.ReadAsStringAsync();
但问题是我不知道如何发布数据?
我已经发送POST请求并发送它里面这些值:注释=Hello World的
和 questionId = 1
。这可以是一个类的属性,我不知道。
But the problem is that I don't know how to post data?
I have to send a post request and send these values inside it: comment="hello world"
and questionId = 1
. these can be a class's properties, I don't know.
更新我不知道如何将这些值添加到 HttpContent
作为post方法需要它。 httClient.Post(字符串,HttpContent);
Update I don't know how to add those values to HttpContent
as post method needs it. httClient.Post(string, HttpContent);
推荐答案
您需要使用方法:
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);
和如果u需要获得职位后的反应,你应该使用:
And if u need to get the response after post, you should use:
var stringContent = await response.Content.ReadAsStringAsync();
希望它帮助;)
Hope it helps ;)
这篇关于如何使用HttpClient的发布数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!