C#http post请求 HttpWebRequest
下面是一个使用HttpWebRequest发送POST请求的示例:
string url = "http://example.com/api";
string postData = "key1=value1&key2=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 (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseText = reader.ReadToEnd();
Console.WriteLine(responseText);
}
}
}
在上述示例中,首先创建了一个HttpWebRequest对象,然后设置请求的URL、请求方法(POST)、请求的内容类型(application/x-www-form-urlencoded)。
接着,将POST数据转换为字节数组,并设置请求的内容长度。
然后,通过GetRequestStream方法获取请求的数据流,并将POST数据写入该流中。
最后,使用GetResponse方法发送请求,并获取响应的数据流。通过StreamReader将数据流转换为字符串,并进行处理
原文地址: http://www.cveoy.top/t/topic/iGf3 著作权归作者所有。请勿转载和采集!