c# webrequest 自动登入网站
这两天用c# 写了一个自动登入网页的小工具。使用的是发送webrequest的方式。
首先,使用抓包工具fiddler抓取登入页面时发送的request。

通过抓包工具,能够获取登入页面时发送的请求,包括以下内容:
request url
request ContentType
request cookie
request contentType
request userAgent
request method
post data 等,
在代码中用以上数据实例化一个HttpWebRequest对象,再把request发送出去即可。下面是代码
string url = "https://10.1.1.1:4100/wgcgi.cgi?action=fw_logon&style=fw_logon.xsl&fw_logon_type=logout"; string postData = Resource1.String1;// postdata 存储在资源文件中 byte[] byteRequest = Encoding.Default.GetBytes(postData); var request = (HttpWebRequest)HttpWebRequest.Create(url); request.CookieContainer = new CookieContainer(); var cookie = new Cookie("domain", "test.com", "/"); request.CookieContainer.Add(new Uri(url), cookie); var cookie1 = new Cookie("username", "san.zhang", "/"); request.CookieContainer.Add(new Uri(url), cookie1); request.Referer = url; request.ContentType = "multipart/form-data; boundary=---------------------------7dd239841324"; request.ContentLength = 920; request.Accept = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E)"; request.Method = WebRequestMethods.Http.Post; request.Timeout = Timeout.Infinite; request.KeepAlive = true; request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate"); request.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN"); ServicePointManager.Expect100Continue = false; Stream stream = request.GetRequestStream(); stream.Write(byteRequest, 0, byteRequest.Length); sw.WriteLine(DateTime.Now + ":" + "send http request and receive response"); // send http request and receive response var response = (HttpWebResponse)request.GetResponse(); // Get html code of reponse page var streamResponsePage = response.GetResponseStream(); StreamReader reader = new StreamReader(streamResponsePage); string html = reader.ReadToEnd(); stream.Close(); reader.Close(); streamResponsePage.Close();
更多抓取网页分析网页的方法请访问:http://www.crifan.com/summary_about_flow_process_of_fetch_webpage_simulate_login_website_and_some_notice/
浙公网安备 33010602011771号