ly/Common/HttpUtil/RequestUtil.cs

421 lines
15 KiB
C#
Raw Permalink Normal View History

2025-03-22 12:16:22 +00:00
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Net;
namespace LY.App.Common.HttpUtil
{
public static class RequestUtil
{
/// <summary>
/// 是否已经初始化加密协议
/// </summary>
private static bool _securitinit = false;
/// <summary>
/// 初始化加密协议
/// </summary>
public static void InitialSecurity()
{
if (_securitinit) return;
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
}
catch (Exception)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
}
catch (Exception)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11;
}
catch (Exception)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
}
catch (Exception) { }
}
}
}
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
_securitinit = true;
}
/// <summary>
/// 获取HTTP连接
/// </summary>
/// <param name="haveSSL">是否ssl连接</param>
/// <returns></returns>
public static HttpClient GetClient(bool haveSSL)
{
if (haveSSL)
{
InitialSecurity();
var handle = new HttpClientHandler();
handle.ServerCertificateCustomValidationCallback
= HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
return new HttpClient(handle);
}
else return new HttpClient();
}
/// <summary>
/// 异步请求GET
/// </summary>
/// <param name="url">网址</param>
/// <param name="headers">头部信息</param>
/// <param name="auth">验证信息</param>
/// <param name="timeout">过期时间</param>
/// <returns></returns>
public static async Task<string> GetAsync(string url,
Dictionary<string, string> headers = null,
AuthenticationHeaderValue auth = null, int timeout = 5000)
{
using (var client = GetClient(url.StartsWith("https")))
{
client.Timeout = TimeSpan.FromMilliseconds(timeout);
if (headers != null && headers.Any())
{
foreach (var item in headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
if (auth != null)
client.DefaultRequestHeaders.Authorization = auth;
var result = await client.GetAsync(url);
if (result.IsSuccessStatusCode)
return await result.Content.ReadAsStringAsync();
}
return null;
}
/// <summary>
/// 异步请求GET
/// </summary>
/// <param name="url">网址</param>
/// <param name="headers">头部信息</param>
/// <param name="auth">验证信息</param>
/// <param name="timeout">过期时间</param>
/// <returns></returns>
public static async Task<Stream> GetStreamAsync(string url,
Dictionary<string, string> headers = null,
AuthenticationHeaderValue auth = null, int timeout = 5000)
{
using (var client = GetClient(url.StartsWith("https")))
{
client.Timeout = TimeSpan.FromMilliseconds(timeout);
if (headers != null && headers.Any())
{
foreach (var item in headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
if (auth != null)
client.DefaultRequestHeaders.Authorization = auth;
var result = await client.GetAsync(url);
if (result.IsSuccessStatusCode)
return await result.Content.ReadAsStreamAsync();
}
return null;
}
/// <summary>
/// 删除
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="auth"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public static async Task<string> DeleteAsync(string url,
Dictionary<string, string> headers = null,
AuthenticationHeaderValue auth = null, int timeout = 5000)
{
using (var client = GetClient(url.StartsWith("https")))
{
client.Timeout = TimeSpan.FromMilliseconds(timeout);
if (headers != null && headers.Any())
{
foreach (var item in headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
if (auth != null)
client.DefaultRequestHeaders.Authorization = auth;
var result = await client.DeleteAsync(url);
if (result.IsSuccessStatusCode)
return await result.Content.ReadAsStringAsync();
}
return null;
}
/// <summary>
/// 异步请求并解析
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">网址</param>
/// <param name="headers">头部信息</param>
/// <param name="auth">验证信息</param>
/// <param name="timeout">过期时间</param>
/// <returns></returns>
public static async Task<T> GetAsync<T>(string url,
Dictionary<string, string> headers = null,
AuthenticationHeaderValue auth = null,
int timeout = 5000)
{
var result = await GetAsync(url, headers, auth, timeout);
if (result != null)
return JsonConvert.DeserializeObject<T>(result);
return default;
}
/// <summary>
/// 返回btye[]
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static async Task<byte[]> GetAsync(string url)
{
using (var client = GetClient(url.StartsWith("https")))
{
client.Timeout = TimeSpan.FromMilliseconds(2000);
var result = await client.GetAsync(url);
if (result.IsSuccessStatusCode)
return await result.Content.ReadAsByteArrayAsync();
}
return null;
}
public static AuthenticationHeaderValue GetTokenHeader(string token)
{
return new AuthenticationHeaderValue("Bearer", token);
}
/// <summary>
/// 异步请求POST
/// </summary>
/// <param name="url">网址</param>
/// <param name="dataJson">信息</param>
/// <param name="headers">头部信息</param>
/// <param name="auth">验证信息</param>
/// <param name="timeout">过期时间</param>
/// <returns></returns>
public static async Task<string> PostAsync(string url,
string dataJson = null,
Dictionary<string, string> headers = null,
AuthenticationHeaderValue auth = null, int timeout = 5000)
{
using (var client = GetClient(url.StartsWith("https")))
{
client.Timeout = TimeSpan.FromMilliseconds(timeout);
if (headers != null && headers.Any())
{
foreach (var item in headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
if (auth != null)
client.DefaultRequestHeaders.Authorization = auth;
StringContent content = null;
if (dataJson != null)
{
content = new StringContent(dataJson);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
var result = await client.PostAsync(url, content);
if (result.IsSuccessStatusCode)
return await result.Content.ReadAsStringAsync();
}
return null;
}
/// <summary>
/// 异步请求POST
/// </summary>
/// <param name="url">网址</param>
/// <param name="data">消息</param>
/// <param name="headers">头部信息</param>
/// <param name="auth">验证信息</param>
/// <param name="timeout">过期时间</param>
/// <returns></returns>
public static async Task<string> PostAsync(string url,
Dictionary<string, string> data,
Dictionary<string, string> headers = null,
AuthenticationHeaderValue auth = null, int timeout = 5000)
{
return await PostAsync(url, JsonConvert.SerializeObject(data), headers, auth, timeout);
}
/// <summary>
/// 异步请求POST
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">网址</param>
/// <param name="dataJson">信息</param>
/// <param name="headers">头部信息</param>
/// <param name="auth">验证信息</param>
/// <param name="timeout">过期时间</param>
/// <returns></returns>
public static async Task<T> PostAsync<T>(string url,
string dataJson = null,
Dictionary<string, string> headers = null,
AuthenticationHeaderValue auth = null, int timeout = 5000)
{
var result = await PostAsync(url, dataJson, headers, auth, timeout);
return JsonConvert.DeserializeObject<T>(result);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">网址</param>
/// <param name="data">消息</param>
/// <param name="headers">头部信息</param>
/// <param name="auth">验证信息</param>
/// <param name="timeout">过期时间</param>
/// <returns></returns>
public static async Task<T> PostAsync<T>(string url,
Dictionary<string, string> data = null,
Dictionary<string, string> headers = null,
AuthenticationHeaderValue auth = null, int timeout = 5000)
{
return await PostAsync<T>(url, JsonConvert.SerializeObject(data), headers, auth, timeout);
}
/// <summary>
/// 异步推送数据流
/// </summary>
/// <param name="url">网址</param>
/// <param name="stream">数据流</param>
/// <param name="headers">头部信息</param>
/// <param name="auth">验证信息</param>
/// <param name="timeout">过期时间</param>
/// <returns></returns>
public static async Task<string> PutStreamAsync(
string url, Stream stream,
Dictionary<string, string> headers = null,
AuthenticationHeaderValue auth = null, int timeout = 10000)
{
using (var client = GetClient(url.StartsWith("https")))
{
client.Timeout = TimeSpan.FromMilliseconds(timeout);
if (headers != null && headers.Any())
{
foreach (var item in headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
if (auth != null)
client.DefaultRequestHeaders.Authorization = auth;
StreamContent content = null;
if (stream != null)
{
content = new StreamContent(stream);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
var result = await client.PutAsync(url, content);
if (result.IsSuccessStatusCode)
return await result.Content.ReadAsStringAsync();
}
return null;
}
/// <summary>
/// 异步推送数据流
/// </summary>
/// <param name="url">网址</param>
/// <param name="stream">数据流</param>
/// <param name="headers">头部信息</param>
/// <param name="auth">验证信息</param>
/// <param name="timeout">过期时间</param>
/// <returns></returns>
public static async Task<T> PutStreamAsync<T>(
string url, Stream stream,
Dictionary<string, string> headers = null,
AuthenticationHeaderValue auth = null, int timeout = 10000)
{
var result = await PutStreamAsync(url, stream, headers, auth, timeout);
return JsonConvert.DeserializeObject<T>(result);
}
/// <summary>
/// PUT请求
/// </summary>
/// <param name="url"></param>
/// <param name="dataJson"></param>
/// <param name="headers"></param>
/// <param name="auth"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public static async Task<string> PutAsync(string url,
string dataJson = null,
Dictionary<string, string> headers = null,
AuthenticationHeaderValue auth = null, int timeout = 5000)
{
using (var client = GetClient(url.StartsWith("https")))
{
client.Timeout = TimeSpan.FromMilliseconds(timeout);
if (headers != null && headers.Any())
{
foreach (var item in headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
if (auth != null)
client.DefaultRequestHeaders.Authorization = auth;
StringContent content = null;
if (dataJson != null)
{
content = new StringContent(dataJson);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
var result = await client.PutAsync(url, content);
if (result.IsSuccessStatusCode)
return await result.Content.ReadAsStringAsync();
}
return null;
}
}
}