httpwebrequest post
时间: 2023-08-25 19:12:36 浏览: 100
好的,您想了解关于使用 C# 的 HttpWebRequest 类发送 POST 请求的方法,是这样吗?如果是的话,以下是一些示例代码:
```csharp
using System;
using System.IO;
using System.Net;
using System.Text;
class Program
{
static void Main(string[] args)
{
string url = "http://example.com/api";
string postData = "param1=value1¶m2=value2";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseText = reader.ReadToEnd();
Console.WriteLine(responseText);
}
}
}
}
}
```
这个示例使用 HttpWebRequest 类向指定 URL 发送 POST 请求,并将返回的响应内容输出到控制台。其中,请求的参数通过 postData 变量传递,并且被编码为 application/x-www-form-urlencoded 格式。
阅读全文