You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
181 lines
5.1 KiB
181 lines
5.1 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Newtonsoft.Json;
|
|
|
|
public class HttpHelper
|
|
{
|
|
private static readonly HttpClient client = new HttpClient();
|
|
|
|
/// <summary>
|
|
/// 判断是否为 URL
|
|
/// </summary>
|
|
public static bool IsUrl(string url)
|
|
{
|
|
if (string.IsNullOrEmpty(url))
|
|
return false;
|
|
|
|
url = url.ToLower();
|
|
return url.StartsWith("http://") || url.StartsWith("https://");
|
|
}
|
|
|
|
/// <summary>
|
|
/// 异步 GET 请求
|
|
/// </summary>
|
|
public static async Task<HttpResponse> HttpGetAsync(string url, int timeout = 10 * 1000)
|
|
{
|
|
try
|
|
{
|
|
// 设置超时时间
|
|
client.Timeout = TimeSpan.FromMilliseconds(timeout);
|
|
|
|
HttpResponseMessage response = await client.GetAsync(url);
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
string content = await response.Content.ReadAsStringAsync();
|
|
return new HttpResponse(response.StatusCode, content);
|
|
}
|
|
catch (HttpRequestException ex)
|
|
{
|
|
Console.WriteLine($"GET Request Error: {ex.Message}");
|
|
return new HttpResponse(HttpStatusCode.BadRequest, $"Error: {ex.Message}");
|
|
}
|
|
catch (TaskCanceledException ex)
|
|
{
|
|
Console.WriteLine($"Request Timeout or Cancelled: {ex.Message}");
|
|
return new HttpResponse(HttpStatusCode.RequestTimeout, "Request timed out.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Unexpected Error: {ex.Message}");
|
|
return new HttpResponse(HttpStatusCode.InternalServerError, $"Unexpected error: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 异步 POST 请求
|
|
/// </summary>
|
|
public static async Task<HttpResponse> HttpPostAsync<T>(string postUrl, T postData, string contentType = "application/json", int timeout = 10 * 1000)
|
|
{
|
|
try
|
|
{
|
|
// 设置超时时间
|
|
client.Timeout = TimeSpan.FromMilliseconds(timeout);
|
|
|
|
string jsonContent = JsonConvert.SerializeObject(postData);
|
|
var content = new StringContent(jsonContent, Encoding.UTF8, contentType);
|
|
|
|
HttpResponseMessage response = await client.PostAsync(postUrl, content);
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
string responseBody = await response.Content.ReadAsStringAsync();
|
|
return new HttpResponse(response.StatusCode, responseBody);
|
|
}
|
|
catch (HttpRequestException ex)
|
|
{
|
|
Console.WriteLine($"POST Request Error: {ex.Message}");
|
|
return new HttpResponse(HttpStatusCode.BadRequest, $"Error: {ex.Message}");
|
|
}
|
|
catch (TaskCanceledException ex)
|
|
{
|
|
Console.WriteLine($"Request Timeout or Cancelled: {ex.Message}");
|
|
return new HttpResponse(HttpStatusCode.RequestTimeout, "Request timed out.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Unexpected Error: {ex.Message}");
|
|
return new HttpResponse(HttpStatusCode.InternalServerError, $"Unexpected error: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据传入的数据,得到相应页面数据(适用于复杂的 HTTP 请求)
|
|
/// </summary>
|
|
public static async Task<HttpResponse> GetHttpRequestDataAsync(HttpItem httpItem)
|
|
{
|
|
using (var requestMessage = new HttpRequestMessage())
|
|
{
|
|
try
|
|
{
|
|
// 设置请求方法
|
|
requestMessage.Method = new HttpMethod(httpItem.Method);
|
|
requestMessage.RequestUri = new Uri(GetUrl(httpItem.URL));
|
|
|
|
// 设置请求头
|
|
foreach (var header in httpItem.Headers ?? Array.Empty<KeyValuePair<string, string>>())
|
|
{
|
|
requestMessage.Headers.Add(header.Key, header.Value);
|
|
}
|
|
|
|
// 设置内容类型
|
|
if (!string.IsNullOrEmpty(httpItem.ContentType))
|
|
{
|
|
requestMessage.Content = new StringContent(httpItem.Postdata!, Encoding.UTF8, httpItem.ContentType);
|
|
}
|
|
|
|
// 设置 Cookie
|
|
if (!string.IsNullOrEmpty(httpItem.Cookie))
|
|
{
|
|
requestMessage.Headers.Add("Cookie", httpItem.Cookie);
|
|
}
|
|
|
|
// 发送请求并获取响应
|
|
HttpResponseMessage response = await client.SendAsync(requestMessage);
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
string content = await response.Content.ReadAsStringAsync();
|
|
return new HttpResponse(response.StatusCode, content);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Request Error: {ex.Message}");
|
|
return new HttpResponse(HttpStatusCode.InternalServerError, $"Error: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 确保 URL 包含协议前缀
|
|
/// </summary>
|
|
private static string GetUrl(string url)
|
|
{
|
|
if (!(url.Contains("http://") || url.Contains("https://")))
|
|
{
|
|
url = "http://" + url;
|
|
}
|
|
return url;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// HTTP 响应结果类
|
|
/// </summary>
|
|
public class HttpResponse
|
|
{
|
|
public HttpStatusCode StatusCode { get; set; }
|
|
public string Content { get; set; }
|
|
|
|
public HttpResponse(HttpStatusCode statusCode, string content)
|
|
{
|
|
StatusCode = statusCode;
|
|
Content = content;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// HTTP 请求项类
|
|
/// </summary>
|
|
public class HttpItem
|
|
{
|
|
public string URL { get; set; } = "";
|
|
public string Method { get; set; } = "GET";
|
|
public int Timeout { get; set; } = 10000;
|
|
public string ContentType { get; set; } = "application/json";
|
|
public string? Postdata { get; set; }
|
|
public string? Cookie { get; set; }
|
|
public KeyValuePair<string, string>[] Headers { get; set; }=new KeyValuePair<string, string>[0];
|
|
}
|