2013-11-15 142 views
40

我有this Nuget的HttpClient。如何使用HttpClient发布数据?

当我想要得到的数据我做这种方式:

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

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

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

+0

不能有人帮忙吗? :) – user2970840

+0

您是否尝试使用Post方法? – Patrick

+0

您应该按照文档中的内容发送您的帖子(如果您正在关注API)。然后,只需填写一个HttpContent并使用[PostAsync](http://msdn.microsoft.com/en-us/library/hh138190(v = vs.110).aspx)你尝试过吗? – Patrick

回答

85

您需要使用:

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

如果u需要获得职位后的反应,你应该使用:

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

希望它有帮助;)

+0

响应是'不可处理的条目'。也许我有一个错误别的 – user2970840

+6

或更短辞典文字某处:'VAR formContent =新FormUrlEncodedContent(新词典<字符串,字符串> { { “注释”,注释}, { “questionId”,questionId} }); ' – hkarask

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

谢谢,但我认为'HttpClient'比'WebClient'好。更简单,更清洁。不是吗? – user2970840

+0

啊,是的,我很习惯WebClient,当我读到这个问题时,我已经记在头脑里了。我还没有使用过HttpClient。抱歉! –