C#写一个HTTP POST通信
以下是一个使用C#发送HTTP POST请求的示例代码:
using System;
using System.Net;
using System.IO;
using System.Text;
class Program
{
static void Main(string[] args)
{
// 设置请求的URL
string url = "https://example.com/api/endpoint";
// 设置POST数据
string postData = "param1=value1¶m2=value2";
// 创建Web请求对象
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
// 发送POST数据
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
}
// 发送请求并获取响应
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string result = reader.ReadToEnd();
Console.WriteLine(result);
}
}
}
上面的代码中,我们首先设置了请求的URL和POST数据,然后创建了一个HttpWebRequest对象。接着,我们设置了请求的方法为POST,设置了请求的Content-Type为application/x-www-form-urlencoded,设置了POST数据的长度,最后通过StreamWriter将POST数据写入请求流中。
然后,我们发送请求并获取响应。使用StreamReader从响应流中读取响应数据,最后将响应数据输出到控制台
原文地址: https://www.cveoy.top/t/topic/e2Gs 著作权归作者所有。请勿转载和采集!