using RestSharp; using RestSharp.Authenticators; using RestSharp.Authenticators.OAuth2; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using YLErp.DBModels; namespace YLErp.Helpers { public class HttpHelper { private string _baseUrl; private Func _tokenFunc; public HttpHelper(string baseUrl, Func tokenFunc = null) { _baseUrl = baseUrl; _tokenFunc = tokenFunc; } public async Task PostRequest(string apiPath, TRequest requestBody) where TRequest : class where TResponse : class { if (string.IsNullOrEmpty(_baseUrl)) { throw new ServiceException("Web Base Url未配置"); } // 创建RestClient var client = new RestClient(_baseUrl); if(_tokenFunc!=null) { client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(_tokenFunc(), "Bearer"); } // 设置token if (_tokenFunc != null) { client.SetJwtToken(_tokenFunc()); } // 创建请求参数 var request = new RestRequest(apiPath, Method.Post); if (requestBody != null) { request.AddBody(requestBody); } // 发送请求并响应结果 var response = await client.ExecuteAsync>(request); return response?.Data?.Data; } public async Task PostRequestNoAuth(string apiPath, TRequest requestBody) where TRequest : class where TResponse : class { if (string.IsNullOrEmpty(_baseUrl)) { throw new ServiceException("Web Base Url未配置"); } // 创建RestClient var client = new RestClient(_baseUrl); // 创建请求参数 var request = new RestRequest(apiPath, Method.Post); if (requestBody != null) { request.AddBody(requestBody); } // 发送请求并响应结果 var response = await client.ExecuteAsync>(request); var responseContent = response.Content; // 检查响应内容是否为空 if (string.IsNullOrEmpty(responseContent)) { throw new ServiceException($"接口返回为空 - URL: {_baseUrl}{apiPath}, StatusCode: {response.StatusCode}"); } return Newtonsoft.Json.JsonConvert.DeserializeObject(responseContent); } public async Task GetRequestNoAuth(string apiPath) where TResponse : class { if (string.IsNullOrEmpty(_baseUrl)) { throw new ServiceException("Web Base Url未配置"); } // 创建 RestClient var client = new RestClient(_baseUrl); // 创建请求参数 var request = new RestRequest(apiPath, Method.Get); // 发送请求并获取响应结果 var response = await client.ExecuteAsync>(request); var responseContent = response.Content; return Newtonsoft.Json.JsonConvert.DeserializeObject(responseContent); } } public static class RestClientExtension { public static void SetJwtToken(this RestClient restClient,string token) { restClient.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(token, "Bearer"); } } public class ReponseWrap { public T Data { get; set; } } }