第三節:總結.Net下後端的幾種請求方式(WebClient、WebRequest、HttpClient)

一. 前言前端

  前端調用有Form表單提交,ajax提交,ajax通常是用Jquery的簡化寫法,在這裏再也不過多介紹; 後端調用大約有這些:WebCient、WebRequest、Httpclient、WebapiClient,重點探討Get和Post請求,Put和Delete請求用較少。ajax

下面排着介紹Get和Post的基本寫法,最後再封裝一下,便於調用。json

PS:其中Post請求有兩種,分別是: "application/x-www-form-urlencoded"表單提交的方式 和 "application/json" Json格式提交的方式。
後端

(1). Post的表單提交的格式爲:"userName=admin&pwd=123456"。api

(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         }

爲了方便下面的測試,給上述三個地址進行命名描述和序列化方法的初始化app

 

二. WebClienttcp

 1. Get請求ide

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 /// <summary>
  2     /// 總結各類請求方式
  3     /// </summary>
  4     public static class RequestWaysHelp
  5     {
  6         #region 01-WebClient的Get請求
  7         /// <summary>
  8         /// WebClient的Get請求
  9         /// </summary>
 10         /// <param name="url">請求地址,含拼接數據,請求格式爲:"http://XXXX?userName=admin&pwd=123456";</param>
 11         /// <returns></returns>
 12         public static string WcGet(string url)
 13         {
 14             WebClient wc = new WebClient();
 15             wc.Encoding = Encoding.UTF8;
 16             return wc.DownloadString(url);
 17         }
 18         #endregion
 19 
 20         #region 02-WebClient的Post請求
 21         /// <summary>
 22         /// WebClient的Post請求
 23         /// 表單提交模式[application/x-www-form-urlencoded]
 24         /// </summary>
 25         /// <param name="url">請求地址,單純的地址,沒有數據拼接</param>
 26         /// <param name="data">請求數據,格式爲:"userName=admin&pwd=123456"</param>
 27         /// <returns></returns>
 28         public static string WcPost1(string url, string data)
 29         {
 30             WebClient wc = new WebClient();
 31             wc.Encoding = Encoding.UTF8;
 32             //也能夠向表頭中添加一些其餘東西
 33             wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
 34             return wc.UploadString(url, data);
 35         }
 36         #endregion
 37 
 38         #region 03-WebClient的Post請求
 39         /// <summary>
 40         /// WebClient的Post請求
 41         /// Json提交模式[application/json]
 42         /// </summary>
 43         /// <param name="url">請求地址,單純的地址,沒有數據拼接</param>
 44         /// <param name="data">請求數據,格式爲(Json)對象、或者類對象 eg: new {id="1"}</param>
 45         /// <returns></returns>
 46         public static string WcPost2(string url, object data)
 47         {
 48             JavaScriptSerializer jss = new JavaScriptSerializer();
 49 
 50             WebClient wc = new WebClient();
 51             wc.Encoding = Encoding.UTF8;
 52             //也能夠向表頭中添加一些其餘東西
 53             wc.Headers.Add("Content-Type", "application/json");
 54             return wc.UploadString(url, jss.Serialize(data));
 55         }
 56         #endregion
 57 
 58         #region 04-HttpWebRequest的Get請求
 59         /// <summary>
 60         /// HttpWebRequest的Get請求
 61         /// </summary>
 62         /// <param name="url">請求地址,含拼接數據,請求格式爲:"http://XXXX?userName=admin&pwd=123456";</param>
 63         /// <returns></returns>
 64         public static string HwGet(string url)
 65         {
 66             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 67             request.Timeout = 30 * 1000;
 68             request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
 69             request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
 70             string result = "";
 71             using (var res = request.GetResponse() as HttpWebResponse)
 72             {
 73                 if (res.StatusCode == HttpStatusCode.OK)
 74                 {
 75                     StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
 76                     result = reader.ReadToEnd();
 77                 }
 78             }
 79             return result;
 80         }
 81         #endregion
 82 
 83         #region 05-HttpWebRequest的Post請求
 84         /// <summary>
 85         /// HttpWebRequest的Post請求
 86         /// 表單提交模式[application/x-www-form-urlencoded]
 87         /// </summary>
 88         /// <param name="url">請求地址,單純的地址,沒有數據拼接</param>
 89         /// <param name="data">請求數據,格式爲:"userName=admin&pwd=123456"</param>
 90         /// <returns></returns>
 91         public static string HwPost1(string url, string data)
 92         {
 93             var request = HttpWebRequest.Create(url) as HttpWebRequest;
 94             request.Timeout = 30 * 1000;//設置30s的超時
 95             request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
 96             request.ContentType = "application/x-www-form-urlencoded";
 97             request.Method = "POST";
 98             byte[] data2 = Encoding.UTF8.GetBytes(data);
 99             request.ContentLength = data2.Length;
100             Stream postStream = request.GetRequestStream();
101             postStream.Write(data2, 0, data2.Length);
102             postStream.Close();
103             string result = "";
104             using (var res = request.GetResponse() as HttpWebResponse)
105             {
106                 if (res.StatusCode == HttpStatusCode.OK)
107                 {
108                     StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
109                     result = reader.ReadToEnd();
110                 }
111             }
112             return result;
113         }
114         #endregion
115 
116         #region 06-HttpWebRequest的Post請求
117         /// <summary>
118         /// HttpWebRequest的Post請求
119         /// Json提交模式[application/json]
120         /// </summary>
121         /// <param name="url">請求地址,單純的地址,沒有數據拼接</param>
122         /// <param name="data">請求數據,格式爲(Json)對象、或者類對象 eg: new {id="1"}</param>
123         /// <returns></returns>
124         public static string HwPost2(string url, object data)
125         {
126             JavaScriptSerializer jss = new JavaScriptSerializer();
127             var postData = jss.Serialize(data);
128             var request = HttpWebRequest.Create(url) as HttpWebRequest;
129             request.Timeout = 30 * 1000; //設置30s的超時
130             request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
131             request.ContentType = "application/json";
132             request.Method = "POST";
133             byte[] data2 = Encoding.UTF8.GetBytes(postData);
134             request.ContentLength = data2.Length;
135             Stream postStream = request.GetRequestStream();
136             postStream.Write(data2, 0, data2.Length);
137             postStream.Close();
138             string result = "";
139             using (var res = request.GetResponse() as HttpWebResponse)
140             {
141                 if (res.StatusCode == HttpStatusCode.OK)
142                 {
143                     StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
144                     result = reader.ReadToEnd();
145                 }
146             }
147             return result;
148         }
149         #endregion
150 
151         #region 07-HttpClient的Get請求
152         /// <summary>
153         /// HttpClient的Get請求
154         /// </summary>
155         ///<param name="url">請求地址,含拼接數據,請求格式爲:"http://XXXX?userName=admin&pwd=123456";</param>
156         /// <returns></returns>
157         public static string HcGet(string url)
158         {
159             var http = HttpClientFactory2.GetHttpClient();
160             var response1 = http.GetAsync(url).Result;
161             return  response1.Content.ReadAsStringAsync().Result;
162         }
163         #endregion
164 
165         #region 08-HttpClient的Post請求
166         /// <summary>
167         /// HttpClient的Post請求
168         /// 表單提交模式[application/x-www-form-urlencoded]
169         /// </summary>
170         /// <param name="url">請求地址,單純的地址,沒有數據拼接</param>
171         /// <param name="data">請求數據,格式爲:"userName=admin&pwd=123456"</param>
172         /// <returns></returns>
173         public static string HcPost1(string url, string data)
174         {
175             var http = HttpClientFactory2.GetHttpClient();
176             var content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
177             var response = http.PostAsync(url, content).Result;
178             return response.Content.ReadAsStringAsync().Result;
179         }
180         #endregion
181 
182         #region 09-HttpClient的Post請求
183         /// <summary>
184         /// HttpClient的Post請求
185         /// Json提交模式[application/json]
186         /// </summary>
187         /// <param name="url">請求地址,單純的地址,沒有數據拼接</param>
188         /// <param name="data">請求數據,格式爲(Json)對象、或者類對象 eg: new {id="1"}</param>
189         /// <returns></returns>
190         public static string HcPost2(string url, object data)
191         {
192             JavaScriptSerializer jss = new JavaScriptSerializer();
193             var http = HttpClientFactory2.GetHttpClient();
194             var content = new StringContent(jss.Serialize(data), Encoding.UTF8, "application/json");
195             var response = http.PostAsync(url, content).Result;
196             return response.Content.ReadAsStringAsync().Result;
197         }
198         #endregion
199 
200 
201     }
202 
203     /// <summary>
204     /// 將HttpClient作成單例的,不用Using,全局只有一個
205     /// 來解決tcp鏈接不能釋放的問題
206     /// </summary>
207     public class HttpClientFactory2
208     {
209         private static HttpClient _httpClient = null;
210 
211         /// <summary>
212         /// 靜態的構造函數:只能有一個,且是無參數的
213         /// 由CLR保證,只有在程序第一次使用該類以前被調用,並且只能調用一次
214         /// 說明: keep-alive關鍵字能夠理解爲一個長連接,超時時間也能夠在上面進行設置,例如10秒的超時時間,固然併發量太大,這個10秒應該會拋棄不少請求
215         /// 發送請求的代碼沒有了using,即這個httpclient不會被手動dispose,而是由系統控制它,固然你的程序重啓時,這也就被回收了。
216         /// </summary>
217         static HttpClientFactory2()
218         {
219             _httpClient = new HttpClient(new HttpClientHandler());
220             _httpClient.Timeout = new TimeSpan(0, 0, 10);
221             _httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
222         }
223 
224         /// <summary>
225         /// 對外開放接口
226         /// </summary>
227         /// <returns></returns>
228         public static HttpClient GetHttpClient()
229         {
230             return _httpClient;
231         }
232     }
RequestWaysHelp

封裝後的調用:

 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                 }

 

 

 

!

  • 做       者 : Yaopengfei(姚鵬飛)
  • 博客地址 : http://www.cnblogs.com/yaopengfei/
  • 聲     明1 : 本人才疏學淺,用郭德綱的話說「我是一個小學生」,若有錯誤,歡迎討論,請勿謾罵^_^。
  • 聲     明2 : 原創博客請在轉載時保留原文連接或在文章開頭加上本人博客地址,不然保留追究法律責任的權利。
相關文章
相關標籤/搜索