请用c#编程封装一个http请求的帮助类
时间: 2024-09-09 15:14:33 浏览: 56
对于C#(HttpClient)方式网络请求的封装
在C#中封装一个HTTP请求的帮助类,你可以使用`HttpClient`类,它提供了发送HTTP请求和接收HTTP响应的功能。以下是一个简单的示例:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class HttpHelper
{
private readonly HttpClient _httpClient;
public HttpHelper(string baseAddress)
{
_httpClient = new HttpClient
{
BaseAddress = new Uri(baseAddress)
};
}
// GET请求
public async Task<string> GetAsync(string requestUri)
{
try
{
HttpResponseMessage response = await _httpClient.GetAsync(requestUri);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
// 处理错误状态码
throw new HttpRequestException($"Error: {response.ReasonPhrase}");
}
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
return string.Empty;
}
}
// POST请求
public async Task<string> PostAsync(string requestUri, StringContent content)
{
try
{
HttpResponseMessage response = await _httpClient.PostAsync(requestUri, content);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
// 处理错误状态码
throw new HttpRequestException($"Error: {response.ReasonPhrase}");
}
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
return string.Empty;
}
}
// 可以继续添加其他HTTP方法的异步封装,比如PUT, DELETE等
}
// 使用示例
public class Program
{
public static async Task Main(string[] args)
{
var httpHelper = new HttpHelper("http://your-api-url.com");
string result = await httpHelper.GetAsync("/api/resource");
Console.WriteLine(result);
}
}
```
这个帮助类提供了GET和POST方法的基本封装。你可以根据需要继续添加PUT、DELETE等其他HTTP方法的实现。同时,根据实际需求,你可能还需要处理HTTP请求头、错误处理、超时设置、取消操作等高级功能。
阅读全文