淺談C#中HttpWebRequest與HttpWebResponse的運用辦法。本站提示廣大學習愛好者:(淺談C#中HttpWebRequest與HttpWebResponse的運用辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是淺談C#中HttpWebRequest與HttpWebResponse的運用辦法正文
這個類是專門為HTTP的GET和POST懇求寫的,處理了編碼,證書,自動帶Cookie等問題。
C# HttpHelper,協助類,真正的Httprequest懇求時無視編碼,無視證書,無視Cookie,網頁抓取
1.第一招,依據URL地址獲取網頁信息
先來看一下代碼
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協議訪問網絡 ///</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.順應於明文,無需登錄,無需任何驗證就可以進入的頁面。
3.獲取的數據類型為HTML文檔。
4.懇求辦法為Get/Post
2.第二招,依據URL地址獲取需求驗證證書才干訪問的網頁信息
先來看一下代碼
get辦法
//回調驗證證書問題 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // 總是承受 return true; } /// <summary> /// 傳入URL前往網頁的html代碼 /// </summary> public string GetUrltoHtml(string Url) { StringBuilder content = new StringBuilder(); try { //這一句一定要寫在創立銜接的後面。運用回調的辦法停止證書驗證。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); // 與指定URL創立HTTP懇求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //創立證書文件 X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer"); //添加到懇求裡 request.ClientCertificates.Add(objx509); // 獲取對應HTTP懇求的呼應 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // 獲取呼應流 Stream responseStream = response.GetResponseStream(); // 對接呼應流(以"GBK"字符集) StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); // 開端讀取數據 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); } // 讀取完畢 sReader.Close(); } catch (Exception) { content = new StringBuilder("Runtime Error"); } return content.ToString(); }
post辦法
//回調驗證證書問題 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // 總是承受 return true; } ///<summary> ///采用https協議訪問網絡 ///</summary> public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding) { // 這一句一定要寫在創立銜接的後面。運用回調的辦法停止證書驗證。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); //創立證書文件 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(); } }
這招是學會算是進了大門了,但凡需求驗證證書才干進入的頁面都可以運用這個辦法進入,我運用的是證書回調驗證的方式,證書驗證能否經過在客戶端驗證,這樣的話我們就可以運用自己定義一個辦法來驗證了,有的人會說那也不清楚是怎樣樣驗證的啊,其它很復雜,代碼是自己寫的為什麼要那麼難為自己呢,直接前往一個True不就完了,永遠都是驗證經過,這樣就可以無視證書的存在了, 特點:
1.入門前的小難題,初級課程。
2.順應於無需登錄,明文但需求驗證證書才干訪問的頁面。
3.獲取的數據類型為HTML文檔。
4.懇求辦法為Get/Post
3.第三招,依據URL地址獲取需求登錄才干訪問的網頁信息
我們先來剖析一下這品種型的網頁,需求登錄才干訪問的網頁,其它呢也是一種驗證,驗證什麼呢,驗證客戶端能否登錄,能否具用相應的憑證,需求登錄的都要驗證SessionID這是每一個需求登錄的頁面都需求驗證的,那我們怎樣做的,我們第一步就是要得存在Cookie外面的數據包括SessionID,那怎樣失掉呢,這個辦法很多,運用ID9或許是火狐閱讀器很容易就能失掉。
提供一個網頁抓取hao123手機號碼歸屬地的例子 這外面針對ID9有詳細的闡明。
假如我們失掉了登錄的Cookie信息之後那個再去訪問相應的頁面就會十分的復雜了,其它說白了就是把本地的Cookie信息在懇求的時分捎帶過來就行了。
看代碼
get辦法
/// <summary> /// 傳入URL前往網頁的html代碼帶有證書的辦法 /// </summary> public string GetUrltoHtml(string Url) { StringBuilder content = new StringBuilder(); try { // 與指定URL創立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 = "*/*"; //假如辦法驗證網頁來源就加上這一句假如不驗證那就可以不寫了 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; // 獲取對應HTTP懇求的呼應 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // 獲取呼應流 Stream responseStream = response.GetResponseStream(); // 對接呼應流(以"GBK"字符集) StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312")); // 開端讀取數據 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); } // 讀取完畢 sReader.Close(); } catch (Exception) { content = new StringBuilder("Runtime Error"); } return content.ToString(); }
post辦法。
///<summary> ///采用https協議訪問網絡 ///</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.還算有點水類型的,練習成功後可以小牛一把。
2.順應於需求登錄才干訪問的頁面。
3.獲取的數據類型為HTML文檔。
4.懇求辦法為Get/Post
總結一下,其它根本的技藝就這幾個局部,假如再深化的話那就是根本技藝的組合了
比方,
1. 先用Get或許Post辦法登錄然後獲得Cookie再去訪問頁面失掉信息,這種其它也是下面技藝的組合,這裡需求以懇求後做這樣一步。response.Cookie
這就是在你懇求後可以失掉當次Cookie的辦法,直接獲得前往給上一個辦法運用就行了,下面我們都是自己結構的,在這裡直接運用這個Cookie就可以了。
2.假如我們碰到需求登錄而且還要驗證證書的網頁怎樣辦,其它這個也很復雜把我們下面的辦法綜合 一下就行了,如下代碼這裡我以Get為例子Post例子也是異樣的辦法
/// <summary> /// 傳入URL前往網頁的html代碼 /// </summary> public string GetUrltoHtml(string Url) { StringBuilder content = new StringBuilder(); try { //這一句一定要寫在創立銜接的後面。運用回調的辦法停止證書驗證。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); // 與指定URL創立HTTP懇求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //創立證書文件 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; // 獲取對應HTTP懇求的呼應 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // 獲取呼應流 Stream responseStream = response.GetResponseStream(); // 對接呼應流(以"GBK"字符集) StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); // 開端讀取數據 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); } // 讀取完畢 sReader.Close(); } catch (Exception) { content = new StringBuilder("Runtime Error"); } return content.ToString(); }
3.假如我們碰到那種需求驗證網頁來源的辦法應該怎樣辦呢,這種狀況其它是有些順序員會想到你能夠會運用順序,自動來獲取網頁信息,為了避免就運用頁面來源來驗證,就是說只需不是從他們所在頁面或是域名過去的懇求就不承受,有的是直接驗證來源的IP,這些都可以運用上面一句來進入,這次要是這個地址是可以直接偽造的
request.Referer = <a href=http://www.jb51.net>http://www.jb51.net</a>;
呵呵其它很復雜由於這個地址可以直接修正。但是假如服務器上驗證的是來源的URL那就完了,我們就得去修正數據包了,這個有點難度暫時不討論。
4.提供一些與這個例子相配置的辦法
過濾HTML標簽的辦法
/// <summary> /// 過濾html標簽 /// </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轉化的辦法
#region 轉化 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來查詢手機號碼歸屬地的辦法,其它在我的上一次文章裡都有,在這裡我再放下去是方便大家閱讀,這方面的技術其它研討起來很有意思,希望大家多提建議,我置信應該還有更多更好,更完善的辦法,在這裡給大家提供一個參考吧。感激支持
上例子
/// <summary> /// 輸出手機號碼失掉歸屬地信息 /// </summary> /// <returns>數組類型0為歸屬地,1卡類型,2區 號,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[] { "歸屬地", "卡類型", "郵 編", "區 號", "更詳細", "卡號" }, 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失掉,但我在這裡的重點是讓一些老手看看辦法和思緒風涼啊,呵呵
第四招,經過Socket訪問
///<summary> /// 懇求的公共類用來向服務器發送懇求 ///</summary> ///<param name="strSMSRequest">發送懇求的字符串</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); //默許80端口號 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //運用tcp協議 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則需求運用對應的Encoding來對字節停止轉換() strSms = strSms + stringData; //strSms += recv.ToString(); } while (recv != 0); socket.Shutdown(SocketShutdown.Both); socket.Close(); return strSms; }
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。