很多時候我們要用HttpWebRequest組件模擬http協議發送web請求,封裝一個請求類看起來就很有必要了。要很好的封裝一個這樣的類,要考慮很多因素,比如通用性和異常處理,甚至還可以是繼承性。當然,我下面要說的是一個靜態類,繼承什么的就算了,簡單封裝一下能用就行,呵呵,太懶了。
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Net; 5 using System.IO; 6 7 namespace Uu102
8 { 9 /// <summary> 10 ///http協議模擬請求類 11 ///主要考慮請求后的具體結果 12 ///此類出自 uu102.com,請尊重原作者,轉載請加上此鏈接 13 /// </summary> 14 class HttpHelper 15 { 16 /// <summary> 17 /// 請求並發限制數目 18 /// </summary> 19 private static int DefaultConnectionLimit=1; 20 private const string Accept = "*/*"; 21 private const string UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)"; 22 private const string ContentType = "application/x-www-form-urlencoded"; 23 24 /// <summary> 25 /// 發送資源請求。返回請求到的響應文本 26 /// 之所以看到這么多形參,只是本人的水平很菜的體現^.^ 27 /// 注意,這個類並沒有處理https加密請求 28 /// </summary> 29 /// <param name="url">發送請求的url地址</param> 30 /// <param name="postString"></param> 31 /// <param name="IsPost"></param> 32 /// <param name="cookieContainer"></param> 33 /// <param name="referer"></param> 34 /// <param name="encoding"></param> 35 /// <returns></returns> 36 public static string GetHtml(string url, string postString, bool IsPost, CookieContainer cookieContainer, string referer, Encoding encoding) 37 { 38 string html = string.Empty; 39 ServicePointManager.Expect100Continue = false; 40 ServicePointManager.DefaultConnectionLimit = DefaultConnectionLimit;//設置並發連接數限制上額 41 DefaultConnectionLimit++; 42 if (string.IsNullOrEmpty(postString)) IsPost = false; 43 HttpWebRequest httpWebRequest = null; 44 45 HttpWebResponse httpWebResponse = null; 46 try 47 { 48 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);//創建連接請求 49 httpWebRequest.Method = IsPost ? "POST" : "GET"; 50 if (cookieContainer != null) httpWebRequest.CookieContainer = cookieContainer; 51 httpWebRequest.AllowAutoRedirect = true;//【注意】這里有個時候在特殊情況下要設置為否,否則會造成cookie丟失 52 httpWebRequest.ContentType = ContentType; 53 httpWebRequest.Accept = Accept; 54 httpWebRequest.UserAgent = UserAgent; 55 if (!string.IsNullOrEmpty(referer)) httpWebRequest.Referer = referer; 56 if (IsPost) //如果是Post遞交數據,則寫入傳的字符串數據 57 { 58 byte[] byteRequest = Encoding.Default.GetBytes(postString); 59 httpWebRequest.ContentLength = byteRequest.Length; 60 Stream stream = httpWebRequest.GetRequestStream(); 61 stream.Write(byteRequest, 0, byteRequest.Length); 62 stream.Close(); 63 } 64 65 httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();//開始獲取響應流 66 Stream responseStream = httpWebResponse.GetResponseStream(); 67 StreamReader streamReader = new StreamReader(responseStream, encoding); 68 html = streamReader.ReadToEnd();//注意這里是直接將所有的字節從頭讀到尾,也可以一行一行的控制,節省時間 69 streamReader.Close(); 70 responseStream.Close(); 71 httpWebRequest.Abort(); 72 73 foreach (Cookie cookie in httpWebResponse.Cookies) //獲取cookie 74 { 75 cookieContainer.Add(cookie); 76 } 77 78 httpWebResponse.Close(); 79 //到這里為止,所有的對象都要釋放掉,以免內存像滾雪球一樣 80 return html; 81 } 82 catch 83 { 84 DefaultConnectionLimit--; 85 //我這里就沒做任何處理了,這里最好還是處理一下 86 return null; 87 } 88 89 } 90 #region 重載方法 91 public static string GetHtml(string url, string postString, CookieContainer cookieContainer, string referer) 92 { 93 return GetHtml(url, postString, true, cookieContainer, referer, Encoding.UTF8); 94 } 95 public static string GetHtml(string url, string postString, CookieContainer cookieContainer) 96 { 97 return GetHtml(url, postString, true, cookieContainer, url, Encoding.UTF8); 98 } 99 public static string GetHtml(string url, CookieContainer cookieContainer, string referer) 100 { 101 return GetHtml(url, "", false, cookieContainer, referer, Encoding.UTF8); 102 } 103 public static string GetHtml(string url, CookieContainer cookieContainer) 104 { 105 return GetHtml(url, "", false, cookieContainer, url, Encoding.UTF8); 106 } 107 public static string GetHtml(string url) 108 { 109 return GetHtml(url, "", true, null, url, Encoding.UTF8); 110 } 111 #endregion 112 /// <summary> 113 /// 這個方法主要用來獲取非文本的html響應正文 114 /// </summary> 115 /// <param name="url"></param> 116 /// <param name="cookieContainer"></param> 117 /// <returns></returns> 118 public static Stream GetStream(string url,CookieContainer cookieContainer) 119 { 120 HttpWebRequest httpWebRequest = null; 121 HttpWebResponse httpWebResponse = null; 122 123 try 124 { 125 126 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); 127 httpWebRequest.CookieContainer = cookieContainer; 128 httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 129 Stream responseStream = httpWebResponse.GetResponseStream(); 130 return responseStream; 131 } 132 catch 133 { 134 if (httpWebRequest != null) 135 { 136 httpWebRequest.Abort(); 137 } if (httpWebResponse != null) 138 { 139 httpWebResponse.Close(); 140 } 141 return null; 142 } 143 } 144 145 } 146 }
代碼太簡單解釋都免了吧?要強調的一點,上面的封裝類還沒有處理https這樣的加密連接,以及返回的status和異常,如果是自己調試,最好是將try這個功能注釋掉,免得看了半天都不知道哪出了問題。
以上的功能雖然能適合絕大部分請求,但是仍有一些請客不適合,比如當模擬上傳文件等等的情況就不適用。
下次我們就聊聊加密請求,以及模擬上傳文件的方法吧!
如果您覺得本文對您有幫助,就請加關注本文博客吧!