Files
SystemX.Web/Projects/NetStandard/CPMeta/RestAPI.cs
2026-02-12 10:59:13 +09:00

83 lines
3.1 KiB
C#

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CPMeta
{
public class RestAPI
{
private static readonly HttpClient RequestClient = new HttpClient();
private static readonly HttpClient ResponseClient = new HttpClient();
public static int TimeOut { get; set; } = 3000;
static RestAPI()
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
RequestClient.Timeout = TimeSpan.FromMilliseconds(TimeOut);
ResponseClient.Timeout = TimeSpan.FromMilliseconds(TimeOut);
}
public static async Task<RESPONSE> PostAsync<REQUEST,RESPONSE>(string Url, REQUEST body, Guid guid) where REQUEST : class where RESPONSE : class
{
try
{
if (body != null)
{
string resContentStr = string.Empty;
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine($"PostAsync:{Url},{JsonConvert.SerializeObject(body, Formatting.Indented)} (Trace Guid: {guid})");
Console.ForegroundColor = ConsoleColor.White;
var jsonBody = JsonConvert.SerializeObject(body);
var contents = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = await RequestClient.PostAsync(Url, contents);
resContentStr = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<RESPONSE>(resContentStr);
}
}
catch (Exception e)
{
Console.WriteLine($"TimeOut: {RequestClient.Timeout}");
Console.WriteLine($"PostAsync Error:{e.Message}");
}
return default(RESPONSE);
}
public static async Task<RESPONSE> GetAsync<RESPONSE>(string Url, Guid guid)
{
try
{
string resContentStr = string.Empty;
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine($"GetAsync:{Url} (Trace Guid: {guid})");
Console.ForegroundColor = ConsoleColor.White;
var response = await ResponseClient.GetAsync(Url);
resContentStr = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<RESPONSE>(resContentStr);
}
catch(Exception e)
{
Console.WriteLine($"TimeOut: {ResponseClient.Timeout}");
Console.WriteLine($"GetAsync Error:{e.Message}");
}
return default(RESPONSE);
}
}
}