(转)总结.Net下后端的几种请求方式(WebClient、WebRequest、HttpClient)
一. 前言
前端调用有Form表单提交,ajax提交,ajax一般是用Jquery的简化写法,在这里不再过多介绍; 后端调用大约有这些:WebCient、WebRequest、Httpclient、WebapiClient,重点探讨Get和Post请求,Put和Delete请求用较少。
下面排着介绍Get和Post的基本写法,最后再封装一下,便于调用。
PS:其中Post请求有两种,分别是: "application/x-www-form-urlencoded"表单提交的方式 和 "application/json" Json格式提交的方式。
(1). Post的表单提交的格式为:"userName=admin&pwd=123456"。
(2). Post的Json的提交格式为:将实体(类)转换成json字符串。
下面先编写几个服务器端的接口方法,便于调用。
1 //Get http://localhost:2131/api/Forth/CheckLogin?userName=admin&pwd=123456 2 [HttpGet] 3 public string CheckLogin(string userName, string pwd) 4 { 5 if (userName == "admin" && pwd == "123456") 6 { 7 return "ok"; 8 } 9 else 10 { 11 return "error"; 12 } 13 } 14 15 16 //Post http://localhost:2131/api/Forth/Register 17 [HttpPost] 18 public string Register([FromBody]LoginModel model) 19 { 20 if (model.userName == "admin" && model.pwd == "123456") 21 { 22 return "ok"; 23 } 24 else 25 { 26 return "error"; 27 } 28 } 29 30 //Post http://localhost:2131/api/Forth/Register2 31 [HttpPost] 32 public string Register2([FromBody]dynamic model) 33 { 34 if (model.userName == "admin" && model.pwd == "123456") 35 { 36 return "ok"; 37 } 38 else 39 { 40 return "error"; 41 } 42 }
为了方便下面的测试,给上述三个地址进行命名描述和序列化方法的初始化
二. WebClient
1. Get请求
1 WebClient wc = new WebClient(); 2 string url = url1; 3 wc.Encoding = Encoding.UTF8; 4 string result = wc.DownloadString(url); 5 Console.WriteLine(result); 6 Console.ReadKey();
2. Post的表单提交方式(url2能访问,url3报500错误)
1 WebClient wc = new WebClient(); 2 string url = url3; 3 wc.Encoding = Encoding.UTF8; 4 //也可以向表头中添加一些其他东西 5 wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 6 string result = wc.UploadString(url, "userName=admin&pwd=123456"); 7 Console.WriteLine(result); 8 Console.ReadKey();
3. Post的JSON提交格式(url2和url3都能正常访问)
1 var user = new 2 { 3 userName = "admin", 4 pwd = "123456" 5 }; 6 WebClient wc = new WebClient(); 7 string url = url3; 8 wc.Encoding = Encoding.UTF8; 9 wc.Headers.Add("Content-Type", "application/json"); 10 string result = wc.UploadString(url, jss.Serialize(user)); 11 Console.WriteLine(result); 12 Console.ReadKey();
三. WebRequest
1. Get请求
1 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1); 2 request.Timeout = 30 * 1000; 3 request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36"; 4 request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; 5 string result = ""; 6 using (var res = request.GetResponse() as HttpWebResponse) 7 { 8 if (res.StatusCode == HttpStatusCode.OK) 9 { 10 StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8); 11 result = reader.ReadToEnd(); 12 } 13 } 14 Console.WriteLine(result); 15 Console.ReadKey();
2. Post的表单提交方式(url2能访问,url3报500错误)
1 var postData = "userName=admin&pwd=123456"; 2 var request = HttpWebRequest.Create(url2) as HttpWebRequest; 3 request.Timeout = 30 * 1000;//设置30s的超时 4 request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36"; 5 request.ContentType = "application/x-www-form-urlencoded"; 6 request.Method = "POST"; 7 byte[] data = Encoding.UTF8.GetBytes(postData); 8 request.ContentLength = data.Length; 9 Stream postStream = request.GetRequestStream(); 10 postStream.Write(data, 0, data.Length); 11 postStream.Close(); 12 string result = ""; 13 using (var res = request.GetResponse() as HttpWebResponse) 14 { 15 if (res.StatusCode == HttpStatusCode.OK) 16 { 17 StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8); 18 result = reader.ReadToEnd(); 19 } 20 } 21 Console.WriteLine(result); 22 Console.ReadKey();
3. Post的JSON提交格式(url2和url3都能正常访问)
1 var user = new 2 { 3 userName = "admin", 4 pwd = "123456" 5 }; 6 var postData = jss.Serialize(user); 7 var request = HttpWebRequest.Create(url2) as HttpWebRequest; 8 request.Timeout = 30 * 1000; //设置30s的超时 9 request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36"; 10 request.ContentType = "application/json"; 11 request.Method = "POST"; 12 byte[] data = Encoding.UTF8.GetBytes(postData); 13 request.ContentLength = data.Length; 14 Stream postStream = request.GetRequestStream(); 15 postStream.Write(data, 0, data.Length); 16 postStream.Close(); 17 string result = ""; 18 using (var res = request.GetResponse() as HttpWebResponse) 19 { 20 if (res.StatusCode == HttpStatusCode.OK) 21 { 22 StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8); 23 result = reader.ReadToEnd(); 24 } 25 } 26 Console.WriteLine(result); 27 Console.ReadKey();
四. HttpClient
1. Get请求
1 var handler = new HttpClientHandler(); 2 using (var http = new HttpClient(handler)) 3 { 4 var response = http.GetAsync(url1).Result; 5 //获取Http的状态值 6 //Console.WriteLine(response.StatusCode); 7 string result = response.Content.ReadAsStringAsync().Result; 8 Console.WriteLine(result); 9 Console.ReadKey(); 10 }
2. Post的表单提交方式(url2能访问,url3报500错误)
1 var handler = new HttpClientHandler(); 2 using (var http = new HttpClient(handler)) 3 { 4 var content = new StringContent("userName=admin&pwd=123456", Encoding.UTF8, "application/x-www-form-urlencoded"); 5 var response = http.PostAsync(url2, content).Result; 6 //获取Http的状态值 7 //Console.WriteLine(response.StatusCode); 8 string result = response.Content.ReadAsStringAsync().Result; 9 Console.WriteLine(result); 10 Console.ReadKey(); 11 }
3. Post的JSON提交格式(url2和url3都能正常访问)
1 var user = new 2 { 3 userName = "admin", 4 pwd = "123456" 5 }; 6 var handler = new HttpClientHandler(); 7 using (var http = new HttpClient(handler)) 8 { 9 var content = new StringContent(jss.Serialize(user), Encoding.UTF8, "application/json"); 10 var response = http.PostAsync(url3, content).Result; 11 //获取Http的状态值 12 //Console.WriteLine(response.StatusCode); 13 string result = response.Content.ReadAsStringAsync().Result; 14 Console.WriteLine(result); 15 Console.ReadKey(); 16 }
注:以上代码均是官方的给出的标准写法,但存在很严重的问题,当请求量大的时候,会存在不能释放的问题,解决方案见下面。
解决方案:
将HttpClient做成单例的,不用Using,全局只有一个,来解决tcp连接不能释放的问题。
1 /// <summary> 2 /// 将HttpClient做成单例的,不用Using,全局只有一个 3 /// 来解决tcp连接不能释放的问题 4 /// </summary> 5 public class HttpClientFactory 6 { 7 private static HttpClient _httpClient = null; 8 9 /// <summary> 10 /// 静态的构造函数:只能有一个,且是无参数的 11 /// 由CLR保证,只有在程序第一次使用该类之前被调用,而且只能调用一次 12 /// 说明: keep-alive关键字可以理解为一个长链接,超时时间也可以在上面进行设置,例如10秒的超时时间,当然并发量太大,这个10秒应该会抛弃很多请求 13 /// 发送请求的代码没有了using,即这个httpclient不会被手动dispose,而是由系统控制它,当然你的程序重启时,这也就被回收了。 14 /// </summary> 15 static HttpClientFactory() 16 { 17 _httpClient = new HttpClient(new HttpClientHandler()); 18 _httpClient.Timeout = new TimeSpan(0, 0, 10); 19 _httpClient.DefaultRequestHeaders.Connection.Add("keep-alive"); 20 } 21 22 /// <summary> 23 /// 对外开放接口 24 /// </summary> 25 /// <returns></returns> 26 public static HttpClient GetHttpClient() 27 { 28 return _httpClient; 29 } 30 }
优化后调用进行Get和Post请求,代码如下
1 var http = HttpClientFactory.GetHttpClient(); 2 //1.Get请求 3 var response1 = http.GetAsync(url1).Result; 4 var result1 = response1.Content.ReadAsStringAsync().Result; 5 Console.WriteLine($"Get请求的返回值为:{result1}"); 6 //2. Post请求【application/x-www-form-urlencoded】 7 var content2 = new StringContent("userName=admin&pwd=123456", Encoding.UTF8, "application/x-www-form-urlencoded"); 8 var response2 = http.PostAsync(url2, content2).Result; 9 string result2 = response2.Content.ReadAsStringAsync().Result; 10 Console.WriteLine($"Post请求【application/x-www-form-urlencoded】的返回值为:{result2}"); 11 //3. Post请求 【application/json】 12 var user = new 13 { 14 userName = "admin", 15 pwd = "123456" 16 }; 17 var content3 = new StringContent(jss.Serialize(user), Encoding.UTF8, "application/json"); 18 var response3 = http.PostAsync(url3, content3).Result; 19 string result3 = response3.Content.ReadAsStringAsync().Result; 20 Console.WriteLine($"Post请求【application/json】的返回值为:{result3}"); 21 Console.ReadKey();
五. 扩展
将WebClient、WebRequest、HttpClient三个类进行封装,其中HttpClient做成单例的,便于我们调用。
封装后的调用:
1 var user = new 2 { 3 userName = "admin", 4 pwd = "123456" 5 }; 6 // WebClient的相关测试 7 { 8 Console.WriteLine("1.WebClient的相关测试"); 9 var result1 = RequestWaysHelp.WcGet(url1); 10 Console.WriteLine(result1); 11 var result2 = RequestWaysHelp.WcPost1(url2, "userName=admin&pwd=123456"); 12 Console.WriteLine(result2); 13 var result3 = RequestWaysHelp.WcPost2(url3, user); 14 Console.WriteLine(result3); 15 } 16 // HttpWebRequest的相关测试 17 { 18 Console.WriteLine("2.HttpWebRequest的相关测试"); 19 var result1 = RequestWaysHelp.HwGet(url1); 20 Console.WriteLine(result1); 21 var result2 = RequestWaysHelp.HwPost1(url2, "userName=admin&pwd=123456"); 22 Console.WriteLine(result2); 23 var result3 = RequestWaysHelp.HwPost2(url3, user); 24 Console.WriteLine(result3); 25 } 26 // HttpClient的相关测试 27 { 28 Console.WriteLine("3.HttpClient的相关测试"); 29 var result1 = RequestWaysHelp.HcGet(url1); 30 Console.WriteLine(result1); 31 var result2 = RequestWaysHelp.HcPost1(url2, "userName=admin&pwd=123456"); 32 Console.WriteLine(result2); 33 var result3 = RequestWaysHelp.HcPost2(url3, user); 34 Console.WriteLine(result3); 35 }
本文来自博客园,作者:NLazyo,转载请注明原文链接:https://www.cnblogs.com/bile/p/15151358.html