c# http post raw
时间: 2023-06-29 12:01:56 浏览: 76
以下是使用 C# 进行 Http Post 请求发送 Raw 数据的示例代码:
```csharp
using System;
using System.IO;
using System.Net;
using System.Text;
class HttpPostRawDemo
{
static void Main()
{
string url = "https://example.com/api/myendpoint";
string contentType = "application/json";
string rawData = "{\"name\":\"John Smith\",\"age\":30,\"city\":\"New York\"}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = contentType;
byte[] dataBytes = Encoding.UTF8.GetBytes(rawData);
request.ContentLength = dataBytes.Length;
using (Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(responseData);
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
```
在上面的示例代码中,我们使用了 `HttpWebRequest` 对象来发送 POST 请求。我们设置了请求的方法为 `POST`,并设置了请求头的 `Content-Type` 为 `application/json`,表示请求体是 JSON 格式的数据。
我们将要发送的数据转成了字节数组,并设置了请求体的长度,然后通过 `GetRequestStream` 方法获取请求体的流,并将数据写入流中。最后,我们通过 `GetResponse` 方法获取响应,并将响应的数据读取出来并输出到控制台上。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)