using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Competition.Common {
public static class HttpHelper {
/// <summary> GET 请求,发送所有指令 </summary>
/// <typeparam name="T"> 传入的元素类型 </typeparam>
/// <param name="url"> </param>
/// <param name="model"> </param>
/// <returns> </returns>
public static async Task<(bool, string)> GetAsync<T>(string url, T model) where T : class, new()
=> await GetAsync(url, DictToUrl<T>(model));
/// <summary> GET 请求,发送所有指令 </summary>
/// <typeparam name="T"> 传入的元素类型 </typeparam>
/// <typeparam name="TResult"> 返回的元素类型 </typeparam>
/// <param name="url"> </param>
/// <param name="model"> </param>
/// <returns> </returns>
public static async Task<(bool, TResult)> GetAsync<T, TResult>(string url, T model) where T : class, new() where TResult : new()
=> await GetAsync<TResult>(url, DictToUrl<T>(model));
/// <summary> GET 请求,发送所有指令 </summary>
/// <param name="url"> </param>
/// <param name="postDataStr"> </param>
/// <returns> </returns>
public static async Task<(bool, string)> GetAsync(string url, string paramsData) {
return await CallGetResultAsync(url, paramsData, (content) => content);
}
/// <summary> GET 请求,发送所有指令 </summary>
/// <param name="url"> </param>
/// <param name="postDataStr"> </param>
/// <returns> </returns>
public static async Task<(bool, T)> GetAsync<T>(string url, string paramsData) where T : new() {
return await CallGetResultAsync(url, paramsData, (content) => JObject.Parse(content).ToObject<T>());
}
private static async Task<(bool, T)> CallGetResultAsync<T>(string url, string paramsData, Func<string, T> func) {
url = url + (paramsData.StartsWith("?") ? "" : "?") + paramsData;
using (var client = new HttpClient()) {
using (var response = await client.GetAsync(url)) {
if (response.IsSuccessStatusCode) {
var resStr = await response.Content.ReadAsStringAsync();
if (resStr != null && func != null) {
var da = func.Invoke(resStr);//处理返回结果
return da != null ? (true, da) : (false, default);
}
}
return (false, default);
}
}
}
/// <summary> post 请求,发送所有指令 </summary>
/// <param name="url"> </param>
/// <param name="postDataStr"> </param>
/// <returns> </returns>
public static async Task<(bool isTrue, TResult res)> Post_JsonAsnyc<TResult>(string url, string postData) where TResult : new() {
return await PostAsnyc<TResult>(url, postData, "application/json");
}
/// <summary> post 请求,发送所有指令 </summary>
/// <param name="url"> </param>
/// <param name="postDataStr"> </param>
/// <returns> </returns>
public static async Task<(bool, string)> Post_JsonAsnyc(string url, string postData) {
return await PostAsnyc(url, postData, "application/json");
}
/// <summary>
///post 请求,发送所有指令
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<(bool, string)> Post_JsonAsnyc<T1>(string url, T1 postData, Dictionary<string, string> headers = null) where T1 : new() {
return await PostAsnyc(url, JsonConvert.SerializeObject(postData), "application/json", headers);
}
/// <summary> post 请求,发送所有指令 </summary>
/// <param name="url"> </param>
/// <param name="postData"> </param>
/// <returns> </returns>
public static async Task<(bool, string)> Post_OctetStreamAsnyc(string url, string postData) {
return await PostAsnyc(url, postData, "application/octet-stream");
}
/// <summary>
///post 请求,发送所有指令
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <returns></returns>
private static async Task<(bool isTrue, string resStr)> PostAsnyc(string url, string postData, string contentType = "application/x-www-form-urlencoded", Dictionary<string, string> headers = null) {
return await CallPostResultAsync(url, postData, contentType, (content) => content, headers);
}
/// <summary> post 请求,发送所有指令 </summary>
/// <param name="url"> </param>
/// <param name="postDataStr"> </param>
/// <returns> </returns>
private static async Task<(bool isTrue, T res)> PostAsnyc<T>(string url, string postData, string contentType = "application/x-www-form-urlencoded") where T : new() {
return await CallPostResultAsync(url, postData, contentType, (content) => JsonConvert.DeserializeObject<T>(content));
}
private static async Task<(bool, T)> CallPostResultAsync<T>(string url, string postData, string contentType, Func<string, T> func, Dictionary<string, string> headers = null) {
HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
using (var client = new HttpClient()) {
if (headers != null) {
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (var response = await client.PostAsync(url, httpContent)) {
if (response.IsSuccessStatusCode) {
var resStr = await response.Content.ReadAsStringAsync();
if (resStr != null && func != null) {
var da = func.Invoke(resStr);//处理返回结果
return da != null ? (true, da) : (false, default);
}
}
return (false, default);
}
}
}
/// <summary> 将字典转换为 url 参数 </summary>
/// <param name="dict"> </param>
/// <returns> </returns>
public static string DictToUrl(Dictionary<string, string> dict) {
//cmd=rt_parse&pnr=ssssss&hk=1
StringBuilder sb = new StringBuilder();
foreach (var item in dict) {
sb.Append(item.Key + "=" + item.Value + "&");
}
return sb.ToString();
}
/// <summary> 将实体类转换为 俩url 参数 </summary>
/// <typeparam name="T"> </typeparam>
/// <param name="t"> </param>
/// <returns> </returns>
public static string DictToUrl<T>(T t) where T : class, new() {
if (t == default(T)) return "";
Type obj = typeof(T);
PropertyInfo[] pArray = obj.GetProperties();
StringBuilder sb = new StringBuilder();
Array.ForEach<PropertyInfo>(pArray, p => {
var val = p.GetValue(t, null);
if (val != null) {
var jsonPro = p.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonPro != null && !string.IsNullOrEmpty(jsonPro.PropertyName)) {
sb.Append(jsonPro.PropertyName + "=" + val + "&");
}
else {
sb.Append(p.Name + "=" + val + "&");
}
}
});
return sb.ToString();
}
}
}