Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用WebClient发送HTTP POST请求_C# - Fatal编程技术网

C# 使用WebClient发送HTTP POST请求

C# 使用WebClient发送HTTP POST请求,c#,C#,我尝试将下一个标题发送到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 Acce

我尝试将下一个标题发送到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
我搜索并发现有一个名为WebClient.UploadData的方法(这个方法隐式地将HTTPPOST设置为请求方法),但我确实没有 知道如何使用它

我知道如何使用Set方法更改当前标题。 但是HTTP正文消息呢?如何在页眉中添加正文?(授权类型)


PS:我读了文档。

除非您处理的是多部分数据,否则不会有太多内容。只需使用post数据构建一个字符串(如果数据需要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);
}

我仅限于出于教育目的使用WebClient。请参阅