HttpClient工具类,实现了Get、Post请求,支持设置超时时间和是否记录错误日志
public class HttpHelper
{
#region HttpClient
/// <summary>
/// Get请求
/// </summary>
/// <param name="url"></param>
/// <param name="timeOut">超时时间:默认10s</param>
/// <param name="isWriteFileLog">是否记录错误日志,默认记录</param>
/// <returns></returns>
/// <exception cref="HttpRequestException"></exception>
public static async Task<string> HttpGetAsync(string url, int timeOut = 10, bool isWriteFileLog = true)
{
string retString = string.Empty;
using HttpClient httpClient = new();
CancellationTokenSource cts = new();
cts.CancelAfter(TimeSpan.FromSeconds(timeOut));
CancellationToken cancellationToken = cts.Token;
try
{
HttpResponseMessage response = await httpClient.GetAsync(url, cancellationToken);
if (response.IsSuccessStatusCode)
{
retString = await response.Content.ReadAsStringAsync();
}
else
{
throw new HttpRequestException($"请求失败: {response.StatusCode}");
}
}
catch (Exception ex)
{
if (isWriteFileLog)
{
LogHelper.Error($"get to [{url}] failed for {ex.Message}", typeof(HttpService), "Get请求");
}
}
return retString;
}
/// <summary>
/// post请求
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <param name="timeOut">超时时间:默认10s</param>
/// <param name="isWriteFileLog">是否记录错误日志,默认记录</param>
/// <returns></returns>
public static async Task<string> HttpPostAsync(string url, string data, int timeOut = 10, bool isWriteFileLog = true)
{
string retString = string.Empty;
using HttpClient httpClient = new();
CancellationTokenSource cts = new();
cts.CancelAfter(TimeSpan.FromSeconds(timeOut));
CancellationToken cancellationToken = cts.Token;
StringContent content = new(data, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await httpClient.PostAsync(url, content, cancellationToken);
if (response.IsSuccessStatusCode)
{
retString = await response.Content.ReadAsStringAsync();
}
else
{
throw new HttpRequestException($"请求失败: {response.StatusCode}");
}
}
catch (Exception ex)
{
if (isWriteFileLog)
{
LogHelper.Error($"post to [{url}] failed for {ex.Message},data is {data}", typeof(HttpService), "Post请求");
}
}
return retString;
}
/// <summary>
/// post表单提交
/// </summary>
/// <param name="url"></param>
/// <param name="dic"></param>
/// <param name="timeOut">超时时间:默认10s</param>
/// <param name="isWriteFileLog">是否记录错误日志,默认记录</param>
/// <returns></returns>
public static async Task<string> HttpPostAsync(string url, Dictionary<string, string> dic, int timeOut = 100, bool isWriteFileLog = true)
{
string retString = string.Empty;
using HttpClient httpClient = new();
CancellationTokenSource cts = new();
cts.CancelAfter(TimeSpan.FromSeconds(timeOut));
CancellationToken cancellationToken = cts.Token;
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
var content = new FormUrlEncodedContent(dic);
try
{
HttpResponseMessage response = await httpClient.PostAsync(url, content, cancellationToken);
if (response.IsSuccessStatusCode)
{
retString = await response.Content.ReadAsStringAsync();
}
else
{
throw new HttpRequestException($"请求失败: {response.StatusCode}");
}
}
catch (Exception ex)
{
if (isWriteFileLog)
{
LogHelper.Error($"post to [{url}] failed for {ex.Message},dic is {JsonConvert.SerializeObject(dic)}", typeof(HttpService), "Post表单提交");
}
}
return retString;
}
#endregion
}
Log日志功能请跳转:C# Log日志功能-CSDN博客