国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

c# HttpWebRequest與HttpWebResponse(轉)

2019-11-17 01:46:26
字體:
來源:轉載
供稿:網友

c# HttpWebRequest與HttpWebResponse(轉)

如果你想做一些,抓取,或者是自動獲取的功能,那么就跟我一起來學習一下Http請求吧。本文章會對Http請求時的Get和Post方式進行詳細的說明,在請求時的參數怎么發(fā)送,怎么帶Cookie,怎么設置證書,怎么解決 編碼等問題,進行一步一步的解決。這個類是專門為HTTP的GET和POST請求寫的,解決了編碼,證書,自動帶Cookie等問題。1.第一招,根據URL地址獲取網頁信息get方法

 1 public static string GetUrltoHtml(string Url,string type) 2         { 3             try 4             { 5                 System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); 6                 // Get the response instance. 7                 System.Net.WebResponse wResp = wReq.GetResponse(); 8                 System.IO.Stream respStream = wResp.GetResponseStream(); 9                 // Dim reader As StreamReader = New StreamReader(respStream)10                 using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))11                 {12                     return reader.ReadToEnd();13                 }14             }15             catch (System.Exception ex)16             {17                 //errorMsg = ex.Message;18             }19             return "";20         }

post方法

 1 ///<summary> 2 ///采用https協(xié)議訪問網絡 3 ///</summary> 4 ///<param name="URL">url地址</param> 5 ///<param name="strPostdata">發(fā)送的數據</param> 6 ///<returns></returns> 7 public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding) 8 { 9     Encoding encoding = Encoding.Default;10     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);11     request.Method = "post";12     request.Accept = "text/html, application/xhtml+xml, */*";13     request.ContentType = "application/x-www-form-urlencoded";14     byte[] buffer = encoding.GetBytes(strPostdata);15     request.ContentLength = buffer.Length;16     request.GetRequestStream().Write(buffer, 0, buffer.Length);17     HttpWebResponse response = (HttpWebResponse)request.GetResponse();18     using( StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding)))19       {20            return reader.ReadToEnd();21       }22 }

這招是入門第一式, 特點: 1.最簡單最直觀的一種,入門課程。 2.適應于明文,無需登錄,無需任何驗證就可以進入的頁面。 3.獲取的數據類型為HTML文檔。 4.請求方法為Get/Post2.第二招,根據URL地址獲取需要驗證證書才能訪問的網頁信息 先來看一下代碼

get方法

 1 //回調驗證證書問題 2 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 3 {    4    // 總是接受     5     return true; 6 } 7   8 /// <summary> 9 /// 傳入URL返回網頁的html代碼10 /// </summary>11 /// <param name="Url">URL</param>12 /// <returns></returns>13 public string GetUrltoHtml(string Url)14 {15     StringBuilder content = new StringBuilder();16  17     try18     {19         //這一句一定要寫在創(chuàng)建連接的前面。使用回調的方法進行證書驗證。20         ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);21  22         // 與指定URL創(chuàng)建HTTP請求23         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);24  25         //創(chuàng)建證書文件26         X509Certificate objx509 = new X509Certificate(Application.StartupPath + "http://123.cer");27  28         //添加到請求里29         request.ClientCertificates.Add(objx509);30  31         // 獲取對應HTTP請求的響應32         HttpWebResponse response = (HttpWebResponse)request.GetResponse();33         // 獲取響應流34         Stream responseStream = response.GetResponseStream();35         // 對接響應流(以"GBK"字符集)36         StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));37         // 開始讀取數據38         Char[] sReaderBuffer = new Char[256];39         int count = sReader.Read(sReaderBuffer, 0, 256);40         while (count > 0)41         {42             String tempStr = new String(sReaderBuffer, 0, count);43             content.Append(tempStr);44             count = sReader.Read(sReaderBuffer, 0, 256);45         }46         // 讀取結束47         sReader.Close();48     }49     catch (Exception)50     {51         content = new StringBuilder("Runtime Error");52     }53  54     return content.ToString();55 }

post方法

 1 //回調驗證證書問題 2 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 3 { 4     // 總是接受     5     return true; 6 } 7   8 ///<summary> 9 ///采用https協(xié)議訪問網絡10 ///</summary>11 ///<param name="URL">url地址</param>12 ///<param name="strPostdata">發(fā)送的數據</param>13 ///<returns></returns>14 public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding)15 {16     // 這一句一定要寫在創(chuàng)建連接的前面。使用回調的方法進行證書驗證。17     ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);18     Encoding encoding = Encoding.Default;19     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);20  21     //創(chuàng)建證書文件22     X509Certificate objx509 = new X509Certificate(Application.StartupPath + "http://123.cer");23  24     //加載Cookie25     request.CookieContainer = new CookieContainer();26  27     //添加到請求里28     request.ClientCertificates.Add(objx509);29     request.Method = "post";30     request.Accept = "text/html, application/xhtml+xml, */*";31     request.ContentType = "application/x-www-form-urlencoded";32     byte[] buffer = encoding.GetBytes(strPostdata);33     request.ContentLength = buffer.Length;34     request.GetRequestStream().Write(buffer, 0, buffer.Length);35     HttpWebResponse response = (HttpWebResponse)request.GetResponse();36     using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding)))37        {38            return reader.ReadToEnd();39        }40 }

這招是學會算是進了大門了,凡是需要驗證證書才能進入的頁面都可以使用這個方法進入,我使用的是證書回調驗證的方式,證書驗證是否通過在客戶端驗證,這樣的話我們就可以使用自己定義一個方法來驗證了,有的人會說那也不清楚是怎么樣驗證的啊,其它很簡單,代碼是自己寫的為什么要那么難為自己呢,直接返回一個True不就完了,永遠都是驗證通過,這樣就可以無視證書的存在了, 特點: 1.入門前的小難題,初級課程。 2.適應于無需登錄,明文但需要驗證證書才能訪問的頁面。 3.獲取的數據類型為HTML文檔。 4.請求方法為Get/Post3.第三招,根據URL地址獲取需要登錄才能訪問的網頁信息 我們先來分析一下這種類型的網頁,需要登錄才能訪問的網頁,其它呢也是一種驗證,驗證什么呢,驗證客戶端是否登錄,是否具用相應的憑證,需要登錄的都要驗證sessionID這是每一個需要登錄的頁面都需要驗證的,那我們怎么做的,我們第一步就是要得存在Cookie里面的數據包括SessionID,那怎么得到呢,這個方法很多,使用ID9或者是火狐瀏覽器很容易就能得到,可以參考我的文章如果我們得到了登錄的Cookie信息之后那個再去訪問相應的頁面就會非常的簡單了,其它說白了就是把本地的Cookie信息在請求的時候捎帶過去就行了。 看代碼

 1 /// <summary> 2 /// 傳入URL返回網頁的html代碼帶有證書的方法 3 /// </summary> 4 /// <param name="Url">URL</param> 5 /// <returns></returns> 6 public string GetUrltoHtml(string Url) 7 { 8     StringBuilder content = new StringBuilder(); 9     try10     {11         // 與指定URL創(chuàng)建HTTP請求12         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);13         request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)";14         request.Method = "GET";15         request.Accept = "*/*";16         //如果方法驗證網頁來源就加上這一句如果不驗證那就可以不寫了17         request.Referer = "http://sufei.VEVb.com";18         CookieContainer objcok = new CookieContainer();19         objcok.Add(new Uri("http://sufei.VEVb.com"), new Cookie("鍵", "值"));20         objcok.Add(new Uri("http://sufei.VEVb.com"), new Cookie("鍵", "值"));21         objcok.Add(new Uri("http://sufei.VEVb.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233"));22         request.CookieContainer = objcok;23  24         //不保持連接25         request.KeepAlive = true;26  27         // 獲取對應HTTP請求的響應28         HttpWebResponse response = (HttpWebResponse)request.GetResponse();29  30         // 獲取響應流31         Stream responseStream = response.GetResponseStream();32  33         // 對接響應流(以"GBK"字符集)34         StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312"));35  36         // 開始讀取數據37         Char[] sReaderBuffer = new Char[256];38         int count = sReader.Read(sReaderBuffer, 0, 256);39         while (count > 0)40         {41             String tempStr = new String(sReaderBuffer, 0, count);42             content.Append(tempStr);43             count = sReader.Read(sReaderBuffer, 0, 256);44         }45         // 讀取結束46         sReader.Close();47     }48     catch (Exception)49
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 桐柏县| 本溪市| 河曲县| 沁水县| 平山县| 林西县| 密云县| 台中县| 泾阳县| 焦作市| 禄劝| 海门市| 义马市| 贵州省| 宁陵县| 通许县| 潍坊市| 金湖县| 什邡市| 夏邑县| 德令哈市| 保德县| 北碚区| 张家港市| 桑日县| 双鸭山市| 湾仔区| 临泉县| 六盘水市| 吴桥县| 章丘市| 平凉市| 南靖县| 恩平市| 贵港市| 公安县| 海南省| 五峰| 铅山县| 竹北市| 迁西县|