淺談C#中HttpWebRequest與HttpWebResponse的使用方法
這個類是專門為HTTP的GET和POST請求寫的,解決了編碼,證書,自動帶Cookie等問題。
C# HttpHelper,幫助類,真正的Httprequest請求時無視編碼,無視證書,無視Cookie,網(wǎng)頁抓取
1.第一招,根據(jù)URL地址獲取網(wǎng)頁信息
先來看一下代碼
get方法
public static string GetUrltoHtml(string Url,string type) { try { System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); // Get the response instance. System.Net.WebResponse wResp = wReq.GetResponse(); System.IO.Stream respStream = wResp.GetResponseStream(); // Dim reader As StreamReader = New StreamReader(respStream) using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type))) { return reader.ReadToEnd(); } } catch (System.Exception ex) { //errorMsg = ex.Message; } return ""; }
post方法
///<summary> ///采用https協(xié)議訪問網(wǎng)絡(luò) ///</summary> public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding) { Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "post"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/x-www-form-urlencoded"; byte[] buffer = encoding.GetBytes(strPostdata); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using( StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding))) { return reader.ReadToEnd(); } }
這招是入門第一式, 特點:
1.最簡單最直觀的一種,入門課程。
2.適應(yīng)于明文,無需登錄,無需任何驗證就可以進入的頁面。
3.獲取的數(shù)據(jù)類型為HTML文檔。
4.請求方法為Get/Post
2.第二招,根據(jù)URL地址獲取需要驗證證書才能訪問的網(wǎng)頁信息
先來看一下代碼
get方法
//回調(diào)驗證證書問題 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // 總是接受 return true; } /// <summary> /// 傳入URL返回網(wǎng)頁的html代碼 /// </summary> public string GetUrltoHtml(string Url) { StringBuilder content = new StringBuilder(); try { //這一句一定要寫在創(chuàng)建連接的前面。使用回調(diào)的方法進行證書驗證。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); // 與指定URL創(chuàng)建HTTP請求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //創(chuàng)建證書文件 X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer"); //添加到請求里 request.ClientCertificates.Add(objx509); // 獲取對應(yīng)HTTP請求的響應(yīng) HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // 獲取響應(yīng)流 Stream responseStream = response.GetResponseStream(); // 對接響應(yīng)流(以"GBK"字符集) StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); // 開始讀取數(shù)據(jù) Char[] sReaderBuffer = new Char[256]; int count = sReader.Read(sReaderBuffer, 0, 256); while (count > 0) { String tempStr = new String(sReaderBuffer, 0, count); content.Append(tempStr); count = sReader.Read(sReaderBuffer, 0, 256); } // 讀取結(jié)束 sReader.Close(); } catch (Exception) { content = new StringBuilder("Runtime Error"); } return content.ToString(); }
post方法
//回調(diào)驗證證書問題 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // 總是接受 return true; } ///<summary> ///采用https協(xié)議訪問網(wǎng)絡(luò) ///</summary> public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding) { // 這一句一定要寫在創(chuàng)建連接的前面。使用回調(diào)的方法進行證書驗證。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); //創(chuàng)建證書文件 X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer"); //加載Cookie request.CookieContainer = new CookieContainer(); //添加到請求里 request.ClientCertificates.Add(objx509); request.Method = "post"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/x-www-form-urlencoded"; byte[] buffer = encoding.GetBytes(strPostdata); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding))) { return reader.ReadToEnd(); } }
這招是學(xué)會算是進了大門了,凡是需要驗證證書才能進入的頁面都可以使用這個方法進入,我使用的是證書回調(diào)驗證的方式,證書驗證是否通過在客戶端驗證,這樣的話我們就可以使用自己定義一個方法來驗證了,有的人會說那也不清楚是怎么樣驗證的啊,其它很簡單,代碼是自己寫的為什么要那么難為自己呢,直接返回一個True不就完了,永遠都是驗證通過,這樣就可以無視證書的存在了, 特點:
1.入門前的小難題,初級課程。
2.適應(yīng)于無需登錄,明文但需要驗證證書才能訪問的頁面。
3.獲取的數(shù)據(jù)類型為HTML文檔。
4.請求方法為Get/Post
3.第三招,根據(jù)URL地址獲取需要登錄才能訪問的網(wǎng)頁信息
我們先來分析一下這種類型的網(wǎng)頁,需要登錄才能訪問的網(wǎng)頁,其它呢也是一種驗證,驗證什么呢,驗證客戶端是否登錄,是否具用相應(yīng)的憑證,需要登錄的都要驗證SessionID這是每一個需要登錄的頁面都需要驗證的,那我們怎么做的,我們第一步就是要得存在Cookie里面的數(shù)據(jù)包括SessionID,那怎么得到呢,這個方法很多,使用ID9或者是火狐瀏覽器很容易就能得到。
提供一個網(wǎng)頁抓取hao123手機號碼歸屬地的例子 這里面針對ID9有詳細(xì)的說明。
如果我們得到了登錄的Cookie信息之后那個再去訪問相應(yīng)的頁面就會非常的簡單了,其它說白了就是把本地的Cookie信息在請求的時候捎帶過去就行了。
看代碼
get方法
/// <summary> /// 傳入URL返回網(wǎng)頁的html代碼帶有證書的方法 /// </summary> public string GetUrltoHtml(string Url) { StringBuilder content = new StringBuilder(); try { // 與指定URL創(chuàng)建HTTP請求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)"; request.Method = "GET"; request.Accept = "*/*"; //如果方法驗證網(wǎng)頁來源就加上這一句如果不驗證那就可以不寫了 request.Referer = "http://txw1958.cnblogs.com"; CookieContainer objcok = new CookieContainer(); objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("鍵", "值")); objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("鍵", "值")); objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233")); request.CookieContainer = objcok; //不保持連接 request.KeepAlive = true; // 獲取對應(yīng)HTTP請求的響應(yīng) HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // 獲取響應(yīng)流 Stream responseStream = response.GetResponseStream(); // 對接響應(yīng)流(以"GBK"字符集) StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312")); // 開始讀取數(shù)據(jù) Char[] sReaderBuffer = new Char[256]; int count = sReader.Read(sReaderBuffer, 0, 256); while (count > 0) { String tempStr = new String(sReaderBuffer, 0, count); content.Append(tempStr); count = sReader.Read(sReaderBuffer, 0, 256); } // 讀取結(jié)束 sReader.Close(); } catch (Exception) { content = new StringBuilder("Runtime Error"); } return content.ToString(); }
post方法。
///<summary> ///采用https協(xié)議訪問網(wǎng)絡(luò) ///</summary> public string OpenReadWithHttps(string URL, string strPostdata) { Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "post"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/x-www-form-urlencoded"; CookieContainer objcok = new CookieContainer(); objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("鍵", "值")); objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("鍵", "值")); objcok.Add(new Uri("http://txw1958.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233")); request.CookieContainer = objcok; byte[] buffer = encoding.GetBytes(strPostdata); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")); return reader.ReadToEnd(); }
特點:
1.還算有點水類型的,練習(xí)成功后可以小牛一把。
2.適應(yīng)于需要登錄才能訪問的頁面。
3.獲取的數(shù)據(jù)類型為HTML文檔。
4.請求方法為Get/Post
總結(jié)一下,其它基本的技能就這幾個部分,如果再深入的話那就是基本技能的組合了
比如,
1. 先用Get或者Post方法登錄然后取得Cookie再去訪問頁面得到信息,這種其它也是上面技能的組合,這里需要以請求后做這樣一步。response.Cookie
這就是在你請求后可以得到當(dāng)次Cookie的方法,直接取得返回給上一個方法使用就行了,上面我們都是自己構(gòu)造的,在這里直接使用這個Cookie就可以了。
2.如果我們碰到需要登錄而且還要驗證證書的網(wǎng)頁怎么辦,其它這個也很簡單把我們上面的方法綜合 一下就行了,如下代碼這里我以Get為例子Post例子也是同樣的方法
/// <summary> /// 傳入URL返回網(wǎng)頁的html代碼 /// </summary> public string GetUrltoHtml(string Url) { StringBuilder content = new StringBuilder(); try { //這一句一定要寫在創(chuàng)建連接的前面。使用回調(diào)的方法進行證書驗證。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); // 與指定URL創(chuàng)建HTTP請求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //創(chuàng)建證書文件 X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer"); //添加到請求里 request.ClientCertificates.Add(objx509); CookieContainer objcok = new CookieContainer(); objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("鍵", "值")); objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("鍵", "值")); objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233")); request.CookieContainer = objcok; // 獲取對應(yīng)HTTP請求的響應(yīng) HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // 獲取響應(yīng)流 Stream responseStream = response.GetResponseStream(); // 對接響應(yīng)流(以"GBK"字符集) StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); // 開始讀取數(shù)據(jù) Char[] sReaderBuffer = new Char[256]; int count = sReader.Read(sReaderBuffer, 0, 256); while (count > 0) { String tempStr = new String(sReaderBuffer, 0, count); content.Append(tempStr); count = sReader.Read(sReaderBuffer, 0, 256); } // 讀取結(jié)束 sReader.Close(); } catch (Exception) { content = new StringBuilder("Runtime Error"); } return content.ToString(); }
3.如果我們碰到那種需要驗證網(wǎng)頁來源的方法應(yīng)該怎么辦呢,這種情況其它是有些程序員會想到你可能會使用程序,自動來獲取網(wǎng)頁信息,為了防止就使用頁面來源來驗證,就是說只要不是從他們所在頁面或是域名過來的請求就不接受,有的是直接驗證來源的IP,這些都可以使用下面一句來進入,這主要是這個地址是可以直接偽造的
request.Referer = <a href=http://www.dbjr.com.cn>http://www.dbjr.com.cn</a>;
呵呵其它很簡單因為這個地址可以直接修改。但是如果服務(wù)器上驗證的是來源的URL那就完了,我們就得去修改數(shù)據(jù)包了,這個有點難度暫時不討論。
4.提供一些與這個例子相配置的方法
過濾HTML標(biāo)簽的方法
/// <summary> /// 過濾html標(biāo)簽 /// </summary> public static string StripHTML(string stringToStrip) { // paring using RegEx // stringToStrip = Regex.Replace(stringToStrip, "</p(?:\\s*)>(?:\\s*)<p(?:\\s*)>", "\n\n", RegexOptions.IgnoreCase | RegexOptions.Compiled); stringToStrip = Regex.Replace(stringToStrip, " ", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled); stringToStrip = Regex.Replace(stringToStrip, "\"", "''", RegexOptions.IgnoreCase | RegexOptions.Compiled); stringToStrip = StripHtmlXmlTags(stringToStrip); return stringToStrip; } private static string StripHtmlXmlTags(string content) { return Regex.Replace(content, "<[^>]+>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled); }
URL轉(zhuǎn)化的方法
#region 轉(zhuǎn)化 URL public static string URLDecode(string text) { return HttpUtility.UrlDecode(text, Encoding.Default); } public static string URLEncode(string text) { return HttpUtility.UrlEncode(text, Encoding.Default); } #endregion
提供一個實際例子,這個是使用IP138來查詢手機號碼歸屬地的方法,其它在我的上一次文章里都有,在這里我再放上來是方便大家閱讀,這方面的技術(shù)其它研究起來很有意思,希望大家多提建議,我相信應(yīng)該還有更多更好,更完善的方法,在這里給大家提供一個參考吧。感謝支持
上例子
/// <summary> /// 輸入手機號碼得到歸屬地信息 /// </summary> /// <returns>數(shù)組類型0為歸屬地,1卡類型,2區(qū) 號,3郵 編</returns> public static string[] getTelldate(string number) { try { string strSource = GetUrltoHtml("http://www.ip138.com:8080/search.asp?action=mobile&mobile=" + number.Trim()); //歸屬地 strSource = strSource.Substring(strSource.IndexOf(number)); strSource = StripHTML(strSource); strSource = strSource.Replace("\r", ""); strSource = strSource.Replace("\n", ""); strSource = strSource.Replace("\t", ""); strSource = strSource.Replace(" ", ""); strSource = strSource.Replace("-->", ""); string[] strnumber = strSource.Split(new string[] { "歸屬地", "卡類型", "郵 編", "區(qū) 號", "更詳細(xì)", "卡號" }, StringSplitOptions.RemoveEmptyEntries); string[] strnumber1 = null; if (strnumber.Length > 4) { strnumber1 = new string[] { strnumber[1].Trim(), strnumber[2].Trim(), strnumber[3].Trim(), strnumber[4].Trim() }; } return strnumber1; } catch (Exception) { return null; } }
這個例子寫是不怎么樣,些地方是可以簡化的,這個接口而且可以直接使用Xml得到,但我在這里的重點是讓一些新手看看方法和思路風(fēng)涼啊,呵呵
第四招,通過Socket訪問
///<summary> /// 請求的公共類用來向服務(wù)器發(fā)送請求 ///</summary> ///<param name="strSMSRequest">發(fā)送請求的字符串</param> ///<returns>返回的是請求的信息</returns> private static string SMSrequest(string strSMSRequest) { byte[] data = new byte[1024]; string stringData = null; IPHostEntry gist = Dns.GetHostByName("www.110.cn"); IPAddress ip = gist.AddressList[0]; //得到IP IPEndPoint ipEnd = new IPEndPoint(ip, 3121); //默認(rèn)80端口號 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //使用tcp協(xié)議 stream類型 try { socket.Connect(ipEnd); } catch (SocketException ex) { return "Fail to connect server\r\n" + ex.ToString(); } string path = strSMSRequest.ToString().Trim(); StringBuilder buf = new StringBuilder(); //buf.Append("GET ").Append(path).Append(" HTTP/1.0\r\n"); //buf.Append("Content-Type: application/x-www-form-urlencoded\r\n"); //buf.Append("\r\n"); byte[] ms = System.Text.UTF8Encoding.UTF8.GetBytes(buf.ToString()); //提交請求的信息 socket.Send(ms); //接收返回 string strSms = ""; int recv = 0; do { recv = socket.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); //如果請求的頁面meta中指定了頁面的encoding為gb2312則需要使用對應(yīng)的Encoding來對字節(jié)進行轉(zhuǎn)換() strSms = strSms + stringData; //strSms += recv.ToString(); } while (recv != 0); socket.Shutdown(SocketShutdown.Both); socket.Close(); return strSms; }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- C#中的HttpWebRequest類介紹
- C#通過HttpWebRequest發(fā)送帶有JSON Body的POST請求實現(xiàn)
- C#中HttpWebRequest、WebClient、HttpClient的使用詳解
- C#使用HttpWebRequest重定向方法詳解
- C#基于HttpWebRequest實現(xiàn)發(fā)送HTTP請求的方法分析
- C#使用HttpWebRequest與HttpWebResponse模擬用戶登錄
- C# httpwebrequest訪問HTTPS錯誤處理方法
- C#中HttpWebRequest的用法詳解
- C#采用HttpWebRequest實現(xiàn)保持會話上傳文件到HTTP的方法
- c# HttpWebRequest通過代理服務(wù)器抓取網(wǎng)頁內(nèi)容應(yīng)用介紹
- C#中的HttpWebRequest類用法詳解
相關(guān)文章
C# 實現(xiàn)對PPT文檔加密、解密及重置密碼的操作方法
這篇文章主要介紹了C# 實現(xiàn)對PPT文檔加密、解密及重置密碼的操作方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-11-11C#根據(jù)反射和特性實現(xiàn)ORM映射實例分析
這篇文章主要介紹了C#根據(jù)反射和特性實現(xiàn)ORM映射的方法,實例分析了反射的原理、特性與ORM的實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04Winform控件Picture實現(xiàn)圖片拖拽顯示效果
這篇文章主要為大家詳細(xì)介紹了Winform控件Picture實現(xiàn)圖片拖拽顯示效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09C#實現(xiàn)創(chuàng)建桌面快捷方式與添加網(wǎng)頁到收藏夾的示例
本文是介紹了c#通過純代碼創(chuàng)建快捷方式與添加網(wǎng)頁到收藏夾,非常具有實用價值,有需要的朋友可以來了解一下。2016-10-10C#中將DataTable轉(zhuǎn)換成CSV文件的方法
DataTable用于在.net項目中,用于緩存數(shù)據(jù),DataTable表示內(nèi)存中數(shù)據(jù)的一個表,在.net項目中運用C#將DataTable轉(zhuǎn)化為CSV文件,接下來通過本文給大家提供一個通用的方法,感興趣的朋友可以參考下2016-10-10