c# 使用 HttpWebRequest類比登陸(附帶驗證碼)

來源:互聯網
上載者:User

在C#中,可以使用HttpWebRequest進行相關的類比登陸,登陸後進行相關的操作,比如抓取資料,頁面分析,製作相關登陸助手等等。

先說下流程

1.使用httpwebrequest先進入你要登入的網站,擷取cookie

2.使用第一步擷取的cookie到驗證碼的網頁將驗證碼下載下來。

3.使用Post資料 發送至網站。如果有cookie則繼續儲存。

4.使用第三步的cookie登陸相關網頁操作。

 

擷取相關資料可以使用抓包工具進行抓取,如httpwatch。(網上下載的好多都有病毒,下載的時候注意點)

1。

/// <summary><br /> /// 通過get方式請求頁面,傳遞一個執行個體化的cookieContainer<br /> /// </summary><br /> /// <param name="postUrl"></param><br /> /// <param name="cookie"></param><br /> /// <returns></returns><br /> public static ArrayList GetHtmlData(string postUrl, CookieContainer cookie)<br /> {<br /> HttpWebRequest request;<br /> HttpWebResponse response;<br /> ArrayList list = new ArrayList();<br /> request = WebRequest.Create(postUrl) as HttpWebRequest;<br /> request.Method = "GET";<br /> request.UserAgent = "Mozilla/4.0";<br /> request.CookieContainer = cookie;<br /> request.KeepAlive = true;</p><p> request.CookieContainer = cookie;<br /> try<br /> {<br /> //擷取伺服器返回的資源<br /> using (response = (HttpWebResponse)request.GetResponse())<br /> {<br /> using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default))<br /> {<br /> cookie.Add(response.Cookies);<br /> //儲存Cookies<br /> list.Add(cookie);<br /> list.Add(reader.ReadToEnd());<br /> list.Add(Guid.NewGuid().ToString());//圖片名<br /> }<br /> }<br /> }<br /> catch (WebException ex)<br /> {<br /> list.Clear();<br /> list.Add("發生異常/n/r");<br /> WebResponse wr = ex.Response;<br /> using (Stream st = wr.GetResponseStream())<br /> {<br /> using (StreamReader sr = new StreamReader(st, System.Text.Encoding.Default))<br /> {<br /> list.Add(sr.ReadToEnd());<br /> }<br /> }<br /> }<br /> catch (Exception ex)<br /> {<br /> list.Clear();<br /> list.Add("5");<br /> list.Add("發生異常:" + ex.Message);<br /> }<br /> return list;<br /> }

2.下載驗證碼,儲存在本地。

/// <summary><br /> /// 下載驗證碼圖片並儲存到本地<br /> /// </summary><br /> /// <param name="Url">驗證碼URL</param><br /> /// <param name="cookCon">Cookies值</param><br /> /// <param name="savePath">儲存位置/檔案名稱</param><br /> public static bool DowloadCheckImg(string Url, CookieContainer cookCon, string savePath)<br /> {<br /> bool bol = true;<br /> HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);<br /> //屬性配置<br /> webRequest.AllowWriteStreamBuffering = true;<br /> webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;<br /> webRequest.MaximumResponseHeadersLength = -1;<br /> webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";<br /> webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";<br /> webRequest.ContentType = "application/x-www-form-urlencoded";<br /> webRequest.Method = "GET";<br /> webRequest.Headers.Add("Accept-Language", "zh-cn");<br /> webRequest.Headers.Add("Accept-Encoding", "gzip,deflate");<br /> webRequest.KeepAlive = true;<br /> webRequest.CookieContainer = cookCon;<br /> try<br /> {<br /> //擷取伺服器返回的資源<br /> using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())<br /> {<br /> using (Stream sream = webResponse.GetResponseStream())<br /> {<br /> List<byte> list = new List<byte>();<br /> while (true)<br /> {<br /> int data = sream.ReadByte();<br /> if (data == -1)<br /> break;<br /> list.Add((byte)data);<br /> }<br /> File.WriteAllBytes(savePath, list.ToArray());<br /> }<br /> }<br /> }<br /> catch (WebException ex)<br /> {<br /> bol = false;<br /> }<br /> catch (Exception ex)<br /> {<br /> bol = false;<br /> }<br /> return bol;<br /> }

3。發送post資料

/// <summary><br /> /// 發送相關資料至頁面<br /> /// 進行登入操作<br /> /// 並儲存cookie<br /> /// </summary><br /> /// <param name="postData"></param><br /> /// <param name="postUrl"></param><br /> /// <param name="cookie"></param><br /> /// <returns></returns><br /> public static ArrayList PostData(string postData, string postUrl, CookieContainer cookie)<br /> {<br /> ArrayList list = new ArrayList();<br /> HttpWebRequest request;<br /> HttpWebResponse response;<br /> ASCIIEncoding encoding = new ASCIIEncoding();<br /> request = WebRequest.Create(postUrl) as HttpWebRequest;<br /> byte[] b = encoding.GetBytes(postData);<br /> request.UserAgent = "Mozilla/4.0";<br /> request.Method = "POST";<br /> request.CookieContainer = cookie;<br /> request.ContentLength = b.Length;<br /> using (Stream stream = request.GetRequestStream())<br /> {<br /> stream.Write(b, 0, b.Length);<br /> }</p><p> try<br /> {<br /> //擷取伺服器返回的資源<br /> using (response = request.GetResponse() as HttpWebResponse)<br /> {<br /> using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))<br /> {<br /> if (response.Cookies.Count > 0)<br /> cookie.Add(response.Cookies);<br /> list.Add(cookie);<br /> list.Add(reader.ReadToEnd());<br /> }<br /> }<br /> }<br /> catch (WebException wex)<br /> {<br /> WebResponse wr = wex.Response;<br /> using (Stream st = wr.GetResponseStream())<br /> {<br /> using (StreamReader sr = new StreamReader(st, System.Text.Encoding.Default))<br /> {<br /> list.Add(sr.ReadToEnd());<br /> }<br /> }<br /> }<br /> catch (Exception ex)<br /> {<br /> list.Add("發生異常/n/r"+ex.Message);<br /> }<br /> return list;<br /> }

4。就是第三步請求的連結地址換一個就行了

 

好了

以上核心代碼已經貼出了

具體實現需要靠你們按照你們自己的邏輯

 

還有一些header能不寫就不寫,因為我2天前一直在擷取返回response這地方報500錯誤。

找了N多代碼,看了N多資料都不可以。最後將一些header注釋掉就可以了,真鬱悶。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.