c# get post
时间: 2023-09-22 22:11:45 浏览: 103
C# post get 参考
C#中获取和发送HTTP请求可以使用HttpClient类。下面是使用HttpClient类进行GET和POST请求的示例代码:
GET请求:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (var client = new HttpClient())
{
var result = await client.GetAsync("https://www.example.com");
var content = await result.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
}
```
POST请求:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (var client = new HttpClient())
{
var data = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("key1", "value1"),
new KeyValuePair<string, string>("key2", "value2")
});
var result = await client.PostAsync("https://www.example.com", data);
var content = await result.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
}
```
上述示例中,使用HttpClient类发送HTTP请求时,首先需要创建一个HttpClient实例。然后,可以使用GetAsync方法发送GET请求,使用PostAsync方法发送POST请求。对于POST请求,需要将请求数据包装成FormUrlEncodedContent对象。最后,使用ReadAsStringAsync方法获取请求结果。
阅读全文