前端js可以使用ajax、axios发出http请求在c#中winform、控制台等可以通过WebRequest、WebClient、HttpClient
有关三个类的性能对比大家可以自己测试一下,这里我主要使用和封装了HttpClient类,对于ResultDto大家可以根据所需进行修改或删除###WebRequest命名空间: System.Net,这是.NET创建者最初开发用于使用HTTP请求的标准类。使用HttpWebRequest可以让开发者控制请求/响应流程的各个方面,如 timeouts, cookies, headers, protocols。另一个好处是HttpWebRequest类不会阻塞UI线程。例如,当您从响应很慢的API服务器下载大文件时,您的应用程序的UI不会停止响应。HttpWebRequest通常和WebResponse一起使用,一个发送请求,一个获取数据。HttpWebRquest更为底层一些,能够对整个访问过程有个直观的认识,但同时也更加复杂一些。简单的使用方法
public static Image RequestGetImage(string requestUrl){return Image.FromStream(WebRequest.Create(requestUrl).GetResponse().GetResponseStream());}
###WebClient命名空间System.Net,WebClient是一种更高级别的抽象,是HttpWebRequest为了简化最常见任务而创建的,使用过程中你会发现他缺少基本的header,timeoust的设置,不过这些可以通过继承httpwebrequest来实现。相对来说,WebClient比WebRequest更加简单,它相当于封装了request和response方法,不过需要说明的是,Webclient和WebRequest继承的是不同类,两者在继承上没有任何关系。使用WebClient可能比HttpWebRequest直接使用更慢(大约几毫秒),但却更为简单,减少了很多细节,代码量也比较少。WebClient我暂时没有使用过###HttpClientHttpClient是.NET4.5引入的一个HTTP客户端库,其命名空间为 System.Net.Http ,.NET 4.5之前我们可能使用WebClient和HttpWebRequest来达到相同目的。HttpClient利用了最新的面向任务模式,使得处理异步请求非常容易。它适合用于多次请求操作,一般设置好默认头部后,可以进行重复多次的请求,基本上用一个实例可以提交任何的HTTP请求。HttpClient有预热机制,第一次进行访问时比较慢,所以不应该用到HttpClient就new一个出来,应该使用单例或其他方式获取HttpClient的实例
public class HttpHelper{private static readonly object LockObj = new object();private static HttpClient client = null;private static readonly string BASE_ADDRESS = "http://localhost:1229/";public HttpHelper(){GetInstance();}/// <summary>/// 制造单例/// </summary>/// <returns></returns>public static HttpClient GetInstance(){if (client == null){lock (LockObj){if (client == null){client = new HttpClient() {BaseAddress = new Uri(BASE_ADDRESS)};}}}return client;}/// <summary>/// 异步Post请求/// </summary>/// <param name="url">请求地址</param>/// <param name="strJson">传入的数据</param>/// <returns></returns>public async Task<string> PostAsync(string url,string strJson){try{HttpContent content = new StringContent(strJson);content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");HttpResponseMessage res = await client.PostAsync(url,content);if (res.StatusCode == System.Net.HttpStatusCode.OK){string resMsgStr = await res.Content.ReadAsStringAsync();return resMsgStr;}else{return null;}}catch (Exception){return null;}}/// <summary>/// 同步Post/// </summary>/// <param name="url"></param>/// <param name="strJson"></param>/// <returns></returns>public string Post(string url, string strJson){try{HttpContent content = new StringContent(strJson);content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");//client.DefaultRequestHeaders.Connection.Add("keep-alive");//由HttpClient发出Post请求Task<HttpResponseMessage> res = client.PostAsync(url, content);if (res.Result.StatusCode == System.Net.HttpStatusCode.OK){string resMsgStr = res.Result.Content.ReadAsStringAsync().Result;return resMsgStr;}else{return null;}}catch (Exception ex){return null;}}/// <summary>/// 异步Post请求/// </summary>/// <typeparam name="TResult">返回参数的数据类型</typeparam>/// <param name="url">请求地址</param>/// <param name="data">传入的数据</param>/// <returns></returns>public async Task<TResult> PostAsync<TResult>(string url, object data){try{var jsonData = JsonConvert.SerializeObject(data);HttpContent content = new StringContent(jsonData);content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");HttpResponseMessage res = await client.PostAsync(url, content);if (res.StatusCode == System.Net.HttpStatusCode.OK){string resMsgStr = await res.Content.ReadAsStringAsync();var result= JsonConvert.DeserializeObject<ResultDto<TResult>>(resMsgStr);return result != null ? result.Data : default;}else{MessageBox.Show(res.StatusCode.ToString());return default;}}catch (Exception ex){MessageBox.Show(ex.Message);return default;}}/// <summary>/// 同步Get请求/// </summary>/// <param name="url">请求地址</param>/// <returns></returns>public string Get(string url){try{var responseString = client.GetStringAsync(url);return responseString.Result;}catch (Exception ex){return null;}}/// <summary>/// 异步Get请求/// </summary>/// <param name="url">请求地址</param>/// <returns></returns>public async Task<string> GetAsync(string url){try{var responseString =await client.GetStringAsync(url);return responseString;}catch (Exception ex){return null;}}/// <summary>/// 异步Get请求/// </summary>/// <typeparam name="TResult">返回参数的数据</typeparam>/// <param name="url">请求地址</param>/// <returns></returns>public async Task<TResult> GetAsync<TResult>(string url){try{var resMsgStr = await client.GetStringAsync(url);var result = JsonConvert.DeserializeObject<ResultDto<TResult>>(resMsgStr);return result != null ? result.Data : default;}catch (Exception ex){return default(TResult);}}}public class ResultDto<TResult>{public string Msg { get; set; }public TResult Data { get; set; }public bool Success { get; set; }}}
记录我在博客园发布的第一篇文章,后续会把本人在csdn的文章都迁移过来https://blog.csdn.net/hyx1229