2013-04-15 95 views
0

我试图unseccessfully到下一个标头中发送到Twitter API发送HTTP POST请求:使用Web客户端

POST /oauth2/token HTTP/1.1 
Host: api.twitter.com 
User-Agent: My Twitter App v1.0.23 
Authorization: Basic eHZ6MWV2R ... o4OERSZHlPZw== 
Content-Type: application/x-www-form-urlencoded;charset=UTF-8 
Content-Length: 29 
Accept-Encoding: gzip 

grant_type=client_credentials 

我搜索,发现有一个名为WebClient.UploadData方法(该方法,隐式地设置HTTP POST作为请求方法),但我真的不知道 知道如何使用它。

我知道如何使用Set方法更改当前标题。 但是,HTTP正文消息呢?我怎样才能添加一些正文头部?(grant_type)

PS:我读了文档。

回答

1

除非您处理多部分数据,否则不会太多。只需建立一个带有发布数据的字符串(如果数据需要,则使用URL编码),获取字节,设置内容长度并将数据写入请求流。

string postData = String.Format("field1=value1&field2=value2"); 
byte[] postBytes = System.Text.ASCIIEncoding.UTF8.GetBytes(postData); 

HttpWebRequest req = HttpWebRequest.Create("http://myurl.com"); 
// ... other request setup stuff 
req.ContentLength = postBytes.Length; 
using (var stream = req.GetRequestStream()) 
{ 
    stream.Write(postBytes, 0, postBytes.Length); 
} 
+0

我仅限于WebClient出于教育目的。 – user1341970

+0

看到http://stackoverflow.com/questions/5401501/how-to-post-data-to-specific-url-using-webclient-in-c-sharp – Yaur

+0

哦,这就是我要找的!谢谢你! – user1341970