c# httpclient 帮助类
时间: 2023-12-05 19:40:14 浏览: 192
以下是一个C#中使用HttpClient的帮助类,包含了常用的HTTP请求方法和一些常见的配置选项:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
public static class HttpClientHelper
{
private static readonly HttpClient _httpClient = new HttpClient();
public static async Task<string> GetAsync(string url)
{
var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public static async Task<byte[]> GetByteArrayAsync(string url)
{
var response = await _httpClient.GetAsync(url); response.EnsureSuccessStatusCode();
return await response.Content.ReadAsByteArrayAsync();
}
public static async Task<string> PostAsync(string url, HttpContent content)
{
var response = await _httpClient.PostAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public static async Task<byte[]> PostByteArrayAsync(string url, HttpContent content)
{
var response = await _httpClient.PostAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsByteArrayAsync();
}
public static async Task<string> PutAsync(string url, HttpContent content)
{
var response = await _httpClient.PutAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public static async Task<byte[]> PutByteArrayAsync(string url, HttpContent content)
{
var response = await _httpClient.PutAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsByteArrayAsync();
}
public static async Task<string> DeleteAsync(string url)
{
var response = await _httpClient.DeleteAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public static async Task<byte[]> DeleteByteArrayAsync(string url)
{
var response = await _httpClient.DeleteAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsByteArrayAsync();
}
public static void SetTimeout(TimeSpan timeout)
{
_httpClient.Timeout = timeout;
}
public static void SetBaseAddress(string baseAddress)
{
_httpClient.BaseAddress = new Uri(baseAddress);
}
public static void SetDefaultRequestHeaders(Action<HttpRequestHeaders> action)
{
action(_httpClient.DefaultRequestHeaders);
}
}
```
使用示例:
```csharp
// 设置基地址
HttpClientHelper.SetBaseAddress("http://localhost:9000/");
// 设置超时时间
HttpClientHelper.SetTimeout(TimeSpan.FromSeconds(10));
// 设置默认请求头
HttpClientHelper.SetDefaultRequestHeaders(headers =>
{
headers.Add("User-Agent", "HttpClientHelper");
});
// 发送GET请求
var response = await HttpClientHelper.GetAsync("index.html");
var content = await response.Content.ReadAsStringAsync();
// 发送POST请求
var content = new StringContent("Hello, world!");
var response = await HttpClientHelper.PostAsync("api/values", content);
var result = await response.Content.ReadAsStringAsync();
```
阅读全文