winform post 请求 json
时间: 2023-09-02 15:02:01 浏览: 264
WinForm 是一个Windows窗体应用程序开发平台,用于开发Windows桌面应用程序。在WinForm中进行Post请求可以使用HttpWebRequest类,来发送Post请求并发送Json数据。
首先需要引用System.Net命名空间,并使用HttpWebRequest类来创建一个HttpWebRequest对象。然后设置请求的URL、请求类型等属性。
接下来,需要设置请求的Content-Type为"application/json",以告诉服务端请求的数据是Json格式的。
然后,通过GetRequestStream方法获取请求的数据流,并把Json数据写入流中。然后关闭流。
使用GetResponse方法发送请求,并获取服务端的响应。
最后,可以通过读取服务端响应的数据流,来获取服务端返回的数据。
以下是一个示例代码:
```csharp
using System;
using System.Net;
using System.Text;
namespace WinFormPostRequestJson
{
class Program
{
static void Main(string[] args)
{
// 请求URL
string url = "http://example.com/api";
// 构造Json数据
string json = "{\"name\":\"John\",\"age\":30}";
// 创建HttpWebRequest对象
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// 设置请求类型为POST
request.Method = "POST";
// 设置请求的Content-Type为"application/json"
request.ContentType = "application/json";
// 把Json数据写入请求的数据流中
byte[] data = Encoding.UTF8.GetBytes(json);
request.GetRequestStream().Write(data, 0, data.Length);
// 发送请求并获取响应
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// 读取响应的数据
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
string result = reader.ReadToEnd();
Console.WriteLine(result);
}
}
// 关闭响应
response.Close();
Console.ReadLine();
}
}
}
```
这样就可以在WinForm应用程序中发送一个Post请求,并且以Json格式发送数据。
阅读全文
相关推荐


















