C#对象调用接口Post提交数据 application/x-www-form-urlencoded 方式
时间: 2024-01-19 19:03:08 浏览: 43
C#调用接口Post提交数据 application/x-www-form-urlencoded 方式可以使用HttpWebRequest类来实现。具体步骤如下:
1. 创建HttpWebRequest对象,并设置请求的URL、请求方法、请求头等信息。
2. 构造请求参数,并将其转换为byte数组。
3. 将请求参数写入请求流中。
4. 发送请求,并获取响应结果。
5. 读取响应流中的数据,并将其转换为字符串格式。
下面是一个示例代码:
```csharp
string EndResult = "";
string SendMessageAddress = "URL";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SendMessageAddress);
request.Method = "POST";
request.AllowAutoRedirect = true;
request.Timeout = 20 * 1000;
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("x-cherun-auth-key", "LarxMbndsxfGwoYAqsfJSPPU42l04cb3");
string PostData = "a=1&b=2";
byte[] byteArray = Encoding.Default.GetBytes(PostData);
request.ContentLength = byteArray.Length;
using (Stream newStream = request.GetRequestStream()) {
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream rspStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8)) {
EndResult = reader.ReadToEnd();
rspStream.Close();
}
response.Close();
```
相关推荐
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)