C#实现一个http请求的工具类
时间: 2024-06-07 09:11:50 浏览: 12
以下是一个简单的 C# HTTP 请求工具类的示例代码:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace HttpUtils
{
public static class HttpHelper
{
public static async Task<string> SendGetRequestAsync(string url)
{
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
return result;
}
else
{
throw new Exception($"HTTP GET request failed with status code {response.StatusCode}.");
}
}
}
public static async Task<string> SendPostRequestAsync(string url, HttpContent content)
{
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
return result;
}
else
{
throw new Exception($"HTTP POST request failed with status code {response.StatusCode}.");
}
}
}
}
}
```
使用示例:
```csharp
using System;
using System.Threading.Tasks;
using HttpUtils;
class Program
{
static async Task Main(string[] args)
{
string response = await HttpHelper.SendGetRequestAsync("https://www.example.com");
Console.WriteLine(response);
}
}
```
以上代码实现了发起 GET 和 POST 请求的方法。你可以根据自己的需求进行修改和扩展。