如何使用HttpClient发布数据?

我从Nuget得到了这个 HttpClient。

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

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

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

更新我不知道如何将这些值添加到HttpContent作为后期方法需要它。 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(); 

希望能帮助到你 ;)

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