前情提要
使用过的一些HTTP请求代码,做个笔记
HttpHelper
public class HttpHelper
{
private static readonly HttpClient _httpClient;
static HttpHelper()
{
_httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(30) // 默认超时时间
};
}
/// <summary>
/// 设置请求头
/// </summary>
/// <param name="headers">请求头键值对</param>
public static void SetHeaders(Dictionary<string, string> headers)
{
_httpClient.DefaultRequestHeaders.Clear();
if (headers != null)
{
foreach (var header in headers)
{
_httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
}
/// <summary>
/// 发送 GET 请求(异步)
/// </summary>
/// <param name="url">请求 URL</param>
/// <returns>响应字符串</returns>
public static async Task<string> GetAsync(string url)
{
try
{
HttpResponseMessage response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
throw new Exception($"GET 请求失败: {ex.Message}");
}
}
/// <summary>
/// 发送 GET 请求(同步)
/// </summary>
/// <param name="url">请求 URL</param>
/// <returns>响应字符串</returns>
public static string Get(string url)
{
try
{
HttpResponseMessage response = _httpClient.GetAsync(url).Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
throw new Exception($"GET 请求失败: {ex.Message}");
}
}
/// <summary>
/// 发送 POST 请求(异步)
/// </summary>
/// <param name="url">请求 URL</param>
/// <param name="data">请求数据,json字符串</param>
/// <param name="contentType">内容类型,默认 application/json</param>
/// <returns>响应字符串</returns>
public static async Task<string> PostAsync(string url, string data, string contentType = "application/json")
{
try
{
var content = new StringContent(data, Encoding.UTF8, contentType);
HttpResponseMessage response = await _httpClient.PostAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
throw new Exception($"POST 请求失败: {ex.Message}");
}
}
/// <summary>
/// 发送 POST 请求(同步)
/// </summary>
/// <param name="url">请求 URL</param>
/// <param name="data">请求数据,json字符串</param>
/// <param name="contentType">内容类型,默认 application/json</param>
/// <returns>响应字符串</returns>
public static string Post(string url, string data, string contentType = "application/json")
{
try
{
var content = new StringContent(data, Encoding.UTF8, contentType);
HttpResponseMessage response = _httpClient.PostAsync(url, content).Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
throw new Exception($"POST 请求失败: {ex.Message}");
}
}
}
调用示例
class Program
{
static async Task Main(string[] args)
{
// 设置请求头
HttpHelper.SetHeaders(new Dictionary<string, string>
{
{ "Authorization", "Bearer your_token_here" }
});
// GET 请求
string getUrl = "https://api.example.com/data";
string getResponse = await HttpHelper.GetAsync(getUrl);
Console.WriteLine($"GET 响应: {getResponse}");
// POST 请求
string postUrl = "https://api.example.com/update";
string postData = "{ \"name\": \"test\", \"value\": 123 }";
string postResponse = await HttpHelper.PostAsync(postUrl, postData);
Console.WriteLine($"POST 响应: {postResponse}");
}
}
评论 (0)