c#编写请求头为application/x-www-form-urlencoded类型的报文
时间: 2024-06-12 22:10:20 浏览: 222
可以使用C#中的HttpWebRequest类来编写请求头为application/x-www-form-urlencoded类型的报文。具体代码如下:
```
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 dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
```
其中,url为请求的地址,postData为请求体中的参数,byteArray为将参数转换为字节数组后的结果。使用HttpWebRequest类的GetRequestStream方法获取请求流,将参数写入请求流中,然后使用GetResponse方法获取响应流并读取响应内容。
阅读全文