简体   繁体   English

使用WebClient发送HTTP POST请求

[英]Sending HTTP POST request using WebClient

I have tried unseccessfully to send the next header to the Twitter API: 我尝试不成功地将下一个标头发送到Twitter API:

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

I searched and found that there's a method called WebClient.UploadData(this method, implicitly sets HTTP POST as the request method) but I dont really know how to work with it. 我搜索后发现有一个名为WebClient.UploadData的方法(此方法隐式将HTTP POST设置为请求方法),但我真的不知道如何使用它。

I know how to change the current headers using Set method. 我知道如何使用Set方法更改当前标头。 But what about the HTTP body message? 但是HTTP正文消息呢? how can I add some body to the header?(grant_type) 如何在标头中添加一些正文?(grant_type)

PS: I read the documention. PS:我看过这篇文章。

Not much to it unless you are dealing with multi-part data. 除非您要处理多部分数据,否则它的功能不多。 Just build a string with the post data (URL encode if the data requires it), get the bytes, set the content-length, and write your data to the request stream. 只需使用发布数据构建一个字符串(如果数据需要,则使用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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM