C#中.NET Framework4.5 封装https GET 带Header参数方法及调用
时间: 2024-09-27 20:06:37 浏览: 29
.NET Framework4.5安装包
在C#的.NET Framework 4.5中,封装一个HTTP GET请求带Header参数通常会使用`HttpClient`类,这是一个线程安全的HTTP客户端API。以下是一个示例,展示了如何创建一个GET请求并添加自定义Header:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class HttpClientWrapper
{
private readonly HttpClient _httpClient;
public HttpClientWrapper()
{
_httpClient = new HttpClient();
// 设置默认的超时时间和取消操作处理
_httpClient.Timeout = TimeSpan.FromSeconds(10);
_httpClient.DefaultRequestHeaders.Add("User-Agent", "YourApp/1.0");
}
public async Task<string> GetAsync(string url, Dictionary<string, string> headers)
{
if (headers != null)
{
foreach (var header in headers)
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
}
HttpResponseMessage response = await _httpClient.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Failed to get data from {url}. Status code: {response.StatusCode}");
}
return await response.Content.ReadAsStringAsync();
}
}
// 调用示例
public static async Task Main()
{
HttpClientWrapper httpClient = new HttpClientWrapper();
var headers = new Dictionary<string, string>
{
{"Authorization", "Bearer your_token"},
{"Content-Type", "application/json"}
};
string result = await httpClient.GetAsync("https://api.example.com/resource", headers);
Console.WriteLine(result);
}
```
在这个例子中,`GetAsync`方法接受URL和包含Header键值对的字典作为参数,然后使用`DefaultRequestHeaders`添加这些Header到请求中。注意替换`"YourApp/1.0"`和`"Bearer your_token"`等实际使用的Header值。
阅读全文