最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来。
十年河东十年河西,莫欺少年穷。
本文旨在发布代码,供自己参考,也供大家参考,谢谢。
正题:
HttpWebClient的四种请求方式:Get、Post、Put、Delete
系列代码如下:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel; using System.Web; namespace WebApiTest { /// <summary> /// 系列代码整理:陈卧龙 18137070152 QQ 1429677330 /// </summary> public class RestServiceProxy { #region static List<T> Get<T>(string endpoint)类型请求 /// <summary> /// HttpClientGet请求 /// </summary> /// <typeparam name="T">泛型</typeparam> /// <param name="endpoint">URL</param> /// <returns></returns> public static List<T> Get<T>(string endpoint) { using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress);//带上请求标题头 var response = httpClient.GetAsync(endpoint).Result; return JsonConvert.DeserializeObject<List<T>>(response.Content.ReadAsStringAsync().Result); } } #endregion #region static T Get<T>(int id, string endpoint)类型请求 public static T Get<T>(int id, string endpoint) { using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); //httpClient.DefaultRequestHeaders.Add("marketcode", GlobalClientConfig.MarketCode);//新宇多带的标题头 //httpClient.DefaultRequestHeaders.Add("languagecode", GlobalClientConfig.LanguageResource); var response = httpClient.GetAsync(endpoint + id).Result; if (response.StatusCode != HttpStatusCode.OK) { if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else { throw new Exception("Invoke Server Service Error"); } } return JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result); } } public static T Get<T>(string id, string endpoint) { T obj; using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var response = httpClient.GetAsync(endpoint + id).Result; if (response.StatusCode != HttpStatusCode.OK) { if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else { throw new Exception("Invoke Server Service Error"); } } string result = response.Content.ReadAsStringAsync().Result; obj = JsonConvert.DeserializeObject<T>(result); return obj; } } #endregion #region Get请求、传递一个对象,返回对象或对象集static T1 Get<T1, T2>(T2 data, string endpoint) /// <summary> /// general get restful service data /// </summary> /// <typeparam name="T1">return data type 返回值类型</typeparam> /// <typeparam name="T2">input data type 参数类型</typeparam> /// <param name="data">search condition</param> /// <param name="endpoint">service url 请求URI</param> /// <returns></returns> public static T1 Get<T1, T2>(T2 data, string endpoint) { using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var _endpoint = endpoint; var requestMessage = GetObjectPropertyValue(data); if (!string.IsNullOrEmpty(requestMessage)) { _endpoint += "?" + requestMessage.Remove(0, 1); } var response = httpClient.GetAsync(_endpoint).Result; if (response.StatusCode != HttpStatusCode.OK) { if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else { throw new Exception("Invoke Server Service Error"); } } string result = response.Content.ReadAsStringAsync().Result; return JsonHelper.JsonDeserialize<T1>(result); } } public static List<T1> GetList<T1, T2>(T2 data, string endpoint) { using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var _endpoint = endpoint; var requestMessage = GetObjectPropertyValue(data); if (!string.IsNullOrEmpty(requestMessage)) { _endpoint += "?" + requestMessage.Remove(0, 1); } var response = httpClient.GetAsync(_endpoint).Result; if (response.StatusCode != HttpStatusCode.OK) { if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else { throw new Exception("Invoke Server Service Error"); } } string result = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<List<T1>>(result); } } #endregion #region Get请求 不/传递Id 返回对象集合 public static List<T1> GetList<T1>(string id, string endpoint) { using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var response = httpClient.GetAsync(endpoint + id).Result; if (response.StatusCode != HttpStatusCode.OK) { if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else { throw new Exception("Invoke Server Service Error"); } } string result = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<List<T1>>(result); } } public static List<T1> GetList<T1>(string endpoint) { using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var response = httpClient.GetAsync(endpoint).Result; if (response.StatusCode != HttpStatusCode.OK) { if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else { throw new Exception("Invoke Server Service Error"); } } string result = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<List<T1>>(result); } } #endregion #region Post请求 static string Post<T>(T data, string endpoint)及 static TRetrun Post<TRetrun, TPost>(TPost data, string endpoint) public static string Post<T>(T data, string endpoint) { using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var requestMessage = JsonHelper.JsonSerializer<T>(data); HttpContent contentPost = new StringContent(requestMessage, Encoding.UTF8, "application/json"); var response = httpClient.PostAsync(endpoint, contentPost).Result; if (response.StatusCode != HttpStatusCode.OK) { if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else { throw new Exception("Invoke Server Service Error"); } } string result = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<string>(result); } } public static TRetrun Post<TRetrun, TPost>(TPost data, string endpoint) { using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var requestMessage = JsonConvert.SerializeObject(data, new IsoDateTimeConverter()); HttpContent contentPost = new StringContent(requestMessage, Encoding.UTF8, "application/json"); var response = httpClient.PostAsync(endpoint, contentPost).Result; if (response.StatusCode != HttpStatusCode.OK) { if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else { throw new Exception("Invoke Server Service Error"); } } string result = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<TRetrun>(result); } } #endregion #region PostByDictionay 字典处理POST public static Dictionary<string, object> PostByDictionay<T>(T data, string endpoint) { using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var requestMessage = JsonHelper.JsonSerializer<T>(data); HttpContent contentPost = new StringContent(requestMessage, Encoding.UTF8, "application/json"); var response = httpClient.PostAsync(endpoint, contentPost).Result; if (response.StatusCode != HttpStatusCode.OK) { if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else { throw new Exception("Invoke Server Service Error"); } } string result = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<Dictionary<string, object>>(result); } } /// <summary> /// 注册设备MAC同步服务器,无需验证 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <param name="endpoint"></param> /// <returns></returns> public static string PostDevice<T>(T data, string endpoint) { using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var requestMessage = JsonHelper.JsonSerializer<T>(data); HttpContent contentPost = new StringContent(requestMessage, Encoding.UTF8, "application/json"); var response = httpClient.PostAsync(endpoint, contentPost).Result; string result = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<string>(result); } } #endregion #region 其他i请求 public static string GetObjectPropertyValue<T>(T t) { StringBuilder sb = new StringBuilder(); Type type = typeof(T); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { if (property != null && t != null) { object o = property.GetValue(t, null); if (o != null) { sb.Append("&" + property.Name + "=" + o); ; } } } return sb.ToString(); } public static T GetOne<T>(string endpoint) { T obj; using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var response = httpClient.GetAsync(endpoint).Result; if (response.StatusCode != HttpStatusCode.OK) { if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else { throw new Exception("Invoke Server Service Error"); } } string result = response.Content.ReadAsStringAsync().Result; obj = JsonConvert.DeserializeObject<T>(result); return obj; } } public static T CheckWhetherInternet<T>(string endpoint) { T obj; using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var response = httpClient.GetAsync(endpoint).Result; if (response.StatusCode != HttpStatusCode.OK) { if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(); } else { throw new Exception("Invoke Server Service Error"); } } string result = response.Content.ReadAsStringAsync().Result; obj = JsonConvert.DeserializeObject<T>(result); return obj; } } #endregion #region Delete 请求 public static string Delete<T>(T data, string endpoint) { using (var httpClient = NewHttpClient()) { httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var _endpoint = endpoint; var requestMessage = GetObjectPropertyValue(data); if (!string.IsNullOrEmpty(requestMessage)) { _endpoint += "?" + requestMessage.Remove(0, 1); } var result = httpClient.DeleteAsync(_endpoint).Result; //return result.Content.ReadAsStringAsync().Result; string res = result.Content.ReadAsStringAsync().Result; return res; } } public static string Delete(string id, string endpoint) { using (var httpClient = NewHttpClient()) { var result = httpClient.DeleteAsync(endpoint + id).Result; return result.Content.ReadAsStringAsync().Result; } } #endregion #region 初始化HttpClient protected static HttpClient NewHttpClient() { var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; return new HttpClient(handler); } #endregion #region 发起Json数据包请求 /// <summary> /// 请求格式JSON数据格式 /// </summary> /// <param name="posturl"></param> /// <param name="postData"></param> /// <returns></returns> public static string GetUri(string posturl, string postData) { using (var http = new HttpClient()) { var content = new StringContent(postData, Encoding.UTF8, "application/json"); //await异步等待回应 var response = http.PostAsync(posturl, content).Result; } return null; } #endregion #region 这是HttpWebRequest请求方式 public static string GetPage(string posturl, string postData) { //WX_SendNews news = new WX_SendNews(); //posturl: news.Posturl; //postData:news.PostData; System.IO.Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 准备请求... try { // 设置参数 request = WebRequest.Create(posturl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } catch (Exception ex) { string err = ex.Message; return string.Empty; } } #endregion } }
@陈卧龙的博客