using RestSharp; using System; using System.Net; namespace EntrustSettle.Common.HttpRestSharp { /// /// 基于 RestSharp 封装HttpHelper /// public static class HttpHelper { /// /// Get 请求 /// /// 泛型 /// 根域名:http://apk.neters.club/ /// 接口:api/xx/yy /// 参数:id=2&name=老张 /// public static T GetApi(string baseUrl, string url, string pragm = "") { var client = new RestSharpClient(baseUrl); var request = client.Execute(string.IsNullOrEmpty(pragm) ? new RestRequest(url, Method.GET) : new RestRequest($"{url}?{pragm}", Method.GET)); if (request.StatusCode != HttpStatusCode.OK) { return (T)Convert.ChangeType(request.ErrorMessage, typeof(T)); } dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(request.Content, typeof(T)); //T result = (T)Convert.ChangeType(request.Content, typeof(T)); return (T)temp; } /// /// Post 请求 /// /// 泛型 /// 完整的url /// post body,可以匿名或者反序列化 /// public static T PostApi(string url, object body = null) { var client = new RestClient($"{url}"); IRestRequest queest = new RestRequest(); queest.Method = Method.POST; queest.AddHeader("Accept", "application/json"); queest.AddJsonBody(body); // 可以使用 JsonSerializer var result = client.Execute(queest); if (result.StatusCode != HttpStatusCode.OK) { return (T)Convert.ChangeType(result.ErrorMessage, typeof(T)); } dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(result.Content, typeof(T)); //T result = (T)Convert.ChangeType(request.Content, typeof(T)); return (T)temp; } } }