c# 写一个post请求带参数的例子

动态 未结 0 112
小小草
小小草 LV1 2023年9月23日 23:40 发表
以下是一个使用C#发送带参数的POST请求的示例: ```csharp using System; using System.Net; using System.IO; using System.Text; class Program { static void Main(string[] args) { string url = "http://example.com/api"; string postData = "param1=value1¶m2=value2"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(byteArray, 0, byteArray.Length); } using (WebResponse response = request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); Console.WriteLine(reader.ReadToEnd()); } } } } ``` 在此示例中,我们首先定义了要发送POST请求的URL和要发送的数据。然后,我们将数据编码为字节数组,并创建一个HttpWebRequest对象来表示请求。我们设置请求方法为“POST”,内容类型为“application/x-www-form-urlencoded”,并设置ContentLength属性以指定请求正文的长度。 接下来,我们使用GetRequestStream()方法获取请求流,并将数据写入该流中。最后,我们使用GetResponse()方法获取响应,并从响应流中读取响应数据。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复