很多時(shí)候我們要用HttpWebRequest組件模擬http協(xié)議發(fā)送web請(qǐng)求,封裝一個(gè)請(qǐng)求類看起來(lái)就很有必要了。要很好的封裝一個(gè)這樣的類,要考慮很多因素,比如通用性和異常處理,甚至還可以是繼承性。當(dāng)然,我下面要說(shuō)的是一個(gè)靜態(tài)類,繼承什么的就算了,簡(jiǎn)單封裝一下能用就行,呵呵,太懶了。

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協(xié)議模擬請(qǐng)求類
11 ///主要考慮請(qǐng)求后的具體結(jié)果
12 ///此類出自 uu102.com,請(qǐng)尊重原作者,轉(zhuǎn)載請(qǐng)加上此鏈接
13 /// </summary>
14 class HttpHelper
15 {
16 /// <summary>
17 /// 請(qǐng)求并發(fā)限制數(shù)目
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 /// 發(fā)送資源請(qǐng)求。返回請(qǐng)求到的響應(yīng)文本
26 /// 之所以看到這么多形參,只是本人的水平很菜的體現(xiàn)^.^
27 /// 注意,這個(gè)類并沒(méi)有處理https加密請(qǐng)求
28 /// </summary>
29 /// <param name="url">發(fā)送請(qǐng)求的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;//設(shè)置并發(fā)連接數(shù)限制上額
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);//創(chuàng)建連接請(qǐng)求
49 httpWebRequest.Method = IsPost ? "POST" : "GET";
50 if (cookieContainer != null) httpWebRequest.CookieContainer = cookieContainer;
51 httpWebRequest.AllowAutoRedirect = true;//【注意】這里有個(gè)時(shí)候在特殊情況下要設(shè)置為否,否則會(huì)造成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遞交數(shù)據(jù),則寫(xiě)入傳的字符串?dāng)?shù)據(jù)
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();//開(kāi)始獲取響應(yīng)流
66 Stream responseStream = httpWebResponse.GetResponseStream();
67 StreamReader streamReader = new StreamReader(responseStream, encoding);
68 html = streamReader.ReadToEnd();//注意這里是直接將所有的字節(jié)從頭讀到尾,也可以一行一行的控制,節(jié)省時(shí)間
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 //到這里為止,所有的對(duì)象都要釋放掉,以免內(nèi)存像滾雪球一樣
80 return html;
81 }
82 catch
83 {
84 DefaultConnectionLimit--;
85 //我這里就沒(méi)做任何處理了,這里最好還是處理一下
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 /// 這個(gè)方法主要用來(lái)獲取非文本的html響應(yīng)正文
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 }

代碼太簡(jiǎn)單解釋都免了吧?要強(qiáng)調(diào)的一點(diǎn),上面的封裝類還沒(méi)有處理https這樣的加密連接,以及返回的status和異常,如果是自己調(diào)試,最好是將try這個(gè)功能注釋掉,免得看了半天都不知道哪出了問(wèn)題。
以上的功能雖然能適合絕大部分請(qǐng)求,但是仍有一些請(qǐng)客不適合,比如當(dāng)模擬上傳文件等等的情況就不適用。