using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace ProjectManagementSystem.WebApiClient.Service { public class RestApi where T : class, new() { public T Get(string url, object pars, object body, out string content) { IRestResponse reval = GetApiInfo(url, pars, body, Method.GET); content = reval.Content; return reval.Data; } public T Post(string url, object pars, object body, out string content) { IRestResponse reval = GetApiInfo(url, pars, body, Method.POST); content = reval.Content; return reval.Data; } public T Delete(string url, object pars, object body, out string content) { IRestResponse reval = GetApiInfo(url, pars, body, Method.DELETE); content = reval.Content; return reval.Data; } public T Put(string url, object pars, object body, out string content) { IRestResponse reval = GetApiInfo(url, pars, body, Method.PUT); content = reval.Content; return reval.Data; } public IRestResponse GetApiInfo(string url, object pars, object body, Method type) { var request = new RestRequest(type); if (pars != null) { request.AddObject(pars); } if (body != null) { request.AddJsonBody(body); } var client = new RestClient(url); //client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("admin", "123456"); //client.CookieContainer = new System.Net.CookieContainer(); //client.ClearHandlers(); //client.AddHandler("text/plain", () => new RestSharp.Serialization.Json.JsonDeserializer()); IRestResponse reval = client.Execute(request); if (reval.ErrorException != null) { throw new Exception($"请求出错 {url} {reval.ErrorMessage} {reval.Content}"); } return reval; } public string RequestUseHttpClient(string url, string data = "", Method requestMethod = Method.POST) { HttpClient http = new HttpClient(new HttpClientHandler() { //启用压缩,节省流量 AutomaticDecompression = DecompressionMethods.GZip }); HttpResponseMessage response = null; switch (requestMethod) { //case Method.: // HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Get, url); // HttpContent hc = new StringContent(data); // hc.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); // hrm.Content = hc; // response = http.SendAsync(hrm).Result; // break; case Method.GET: http.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded"); response = http.GetAsync(url).Result; break; case Method.POST: HttpContent httpContent = new StringContent(data); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response = http.PostAsync(url, httpContent).Result; break; case Method.PUT: HttpContent putContent = new StringContent(data); putContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response = http.PutAsync(url, putContent).Result; break; default: break; } var res = response?.Content.ReadAsStringAsync().Result; return res; } } }