C# winform网页登录和POST提交信息的多种方法

11/4/2016 3:10:04 PM

技术应用——网页自动登录(提交Post内容)的用途很多,如验证身份、程序升级、网络投票等,以下是用C#实现的方法.

页自动登录和提交POST信息的核心就是分析网页的源代码(HTML),在C#中,可以用来提取网页HTML的组件比较多,常用的用WebBrowser、WebClient、HttpWebRequest这三个。

以下就分别用这三种方法来实现:
1、WebBrowser是个"迷你"浏览器,其特点是Post时不用关心Cookie、内置JS等问题
WebBrowser是VS提供的组件(其实就是封装了IE接口),实现POST功能一般在webBrowser的DocumentCompleted中分析HtmlDocument 来实现,代码如下:


 
  1. HtmlElement ClickBtn =null;
  2. if (e.Url.ToString().ToLower().IndexOf("http://oceanchen.cnblogs.com/") > 0) //登陆页面
  3. {
  4. HtmlDocument doc = webBrowser1.Document;
  5. for (int i = 0; i < doc.All.Count ; i++)
  6. {
  7. if (doc.All[i].TagName.ToUpper().Equals("INPUT"))
  8. {
  9. switch (doc.All[i].Name)
  10. {
  11. case "userCtl":
  12. doc.All[i].InnerText = "user01";
  13. break;
  14. case "passCt1":
  15. doc.All[i].InnerText = "mypass";
  16. break;
  17. case "B1":
  18. ClickBtn = doc.All[i]; //提交按钮
  19. break;
  20. }
  21. }
  22. }
  23. ClickBtn.InvokeMember("Click"); //执行按扭操作
  24. }

2、WebClient封装了HTTP的一些类,操作简单,相较于webBrowser,特点是可以自设代理,缺点是对COOKIE的控制
WebClient的运行全在后台,并且提供了异步操作的能力,这样很方便并发多个任务,然后等待结果的返回,再逐个处理。多任务异步调用的代码如下:


 
  1. private void StartLoop(int ProxyNum)
  2. {
  3. WebClient [] wcArray = new WebClient[ProxyNum]; //初始化
  4. for (int idArray = 0; idArray< ProxyNum;idArray++)
  5. {
  6. wcArray[idArray] = new WebClient();
  7. wcArray[idArray].OpenReadCompleted += new OpenReadCompletedEventHandler(Pic_OpenReadCompleted2);
  8. wcArray[idArray].UploadDataCompleted += new UploadDataCompletedEventHandler(Pic_UploadDataCompleted2);
  9. try
  10. {
  11.  
  12. wcArray[idArray].Proxy = new WebProxy(proxy[1], port);
  13. wcArray[idArray].OpenReadAsync(new Uri("http://oceanchen.cnblogs.com/")); //打开WEB;
  14. proxy = null;
  15. }
  16. catch
  17. {
  18. }
  19. }
  20. }
  21.  
  22. private void Pic_OpenReadCompleted2(object sender, OpenReadCompletedEventArgs e)
  23. {
  24. if (e.Error == null)
  25. {
  26. string textData = new StreamReader(e.Result, Encoding.Default).ReadToEnd(); //取返回信息
  27. ..
  28. String cookie = ((WebClient)sender).ResponseHeaders["Set-Cookie"];
  29. ((WebClient)sender).Headers.Add("Content-Type", "application/x-www-form-urlencoded");
  30. ((WebClient)sender).Headers.Add("Accept-Language", "zh-cn");
  31. ((WebClient)sender).Headers.Add("Cookie", cookie);
  32.  
  33. string postData = ""
  34. byte[] byteArray = Encoding.UTF8.GetBytes(postData); // 转化成二进制数组
  35. ((WebClient)sender).UploadDataAsync(new Uri("http://oceanchen.cnblogs.com/"), "POST", byteArray);
  36. }
  37. }
  38.  
  39. private void Pic_UploadDataCompleted2(object sender, UploadDataCompletedEventArgs e)
  40. {
  41. if (e.Error == null)
  42. {
  43. string returnMessage = Encoding.Default.GetString(e.Result);
  44.  
  45. }
  46. }

3、HttpWebRequest较为低层,能实现的功能较多,Cookie操作也很简单:


 
  1. private bool PostWebRequest()
  2. {
  3. CookieContainer cc = new CookieContainer();
  4. string pos tData = "user=" + strUser + "&pass=" + strPsd;
  5. byte[] byteArray = Encoding.UTF8.GetBytes(postData); // 转化
  6.  
  7. HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(new Uri(http://oceanchen.cnblogs.com/));
  8. webRequest2.CookieContainer = cc;
  9. webRequest2.Method = "POST";
  10. webRequest2.ContentType = "application/x-www-form-urlencoded";
  11. webRequest2.ContentLength = byteArray.Length;
  12. Stream newStream = webRequest2.GetRequestStream();
  13. // Send the data.
  14. newStream.Write(byteArray, 0, byteArray.Length); //写入参数
  15. newStream.Close();
  16.  
  17. HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
  18. StreamReader sr2=new StreamReader(response2.GetResponseStream(), Encoding.Default);
  19. string text2 = sr2.ReadToEnd();
  20.  
  21. }

HttpWebRequest 实现, 这个是从网上COPY 的!我以前用相关的代码登录到WWW.ASP.NET上,并且成功post,可惜代码不知道放什么地方了。

 

HttpWebRequest自动登录网站并获取网站内容(不包含验证码的网站)

可以使用 Visual Sniffer(百度搜索) 来捕捉提交的数据信息:

1. 访问你需要站外提交的页面,比如 CSDN 登陆页 http://www.csdn.net/member/UserLogin.aspx

2. 填写好需要的资料,比如用户名和密码,

3. 打开 Visual Sniffer, 点“开始拦截”

4. 在访问的页面中提交。

5. 等提交成功之后,在 Visual Sniffer 中“停止拦截”

6. 在 Visual Sniffer 的左侧栏的加号中依次点开,右边是它拦截到的内容:


 
  1. POST http://www.csdn.net/member/UserLogin.aspx HTTP/1.0
  2. Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
  3. Referer: http://www.csdn.net/member/UserLogin.aspx
  4. Accept-Language: zh-cn
  5. Content-Type: application/x-www-form-urlencoded
  6. UA-CPU: x86
  7. Pragma: no-cache
  8. User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; InfoPath.1)
  9. Host: www.csdn.net
  10. Content-Length: 355
  11. Proxy-Connection: Keep-Alive
  12. Cookie: ASPSESSIONIDAAAATBQC=FMEGGCKDBKHAMMCGKPFDMBFG; ASP.NET_SessionId=lusprmnom05lr445tmteaf55; userid=699879
  13.  
  14. __EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=dDwtMTcwMzgxNjQ2Mjs7bDxDU0ROVXNlckxvZ2luOmNiX1NhdmVTdGF0ZTtDU0ROVXNlckxvZ2luOkltYWdlX0xvZ2luOz4%2Btu1q2wmRZoAJTi9L73w1zBleylY%3D&CSDNUserLogin%3Atb_UserName=testusername&CSDNUserLogin%3Atb_Password=testpassword&CSDNUserLogin%3Atb_ExPwd=9232&from=&CSDNUserLogin%3AImage_Login.x=36&CSDNUserLogin%3AImage_Login.y=6
  15. GET http://www.csdn.net/mycustompage.htm?aspxerrorpath=/member/UserLogin.aspx HTTP/1.0
  16. Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
  17. Referer: http://www.csdn.net/member/UserLogin.aspx
  18. Accept-Language: zh-cn
  19. UA-CPU: x86
  20. Pragma: no-cache
  21. User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; InfoPath.1)
  22. Host: www.csdn.net
  23. Proxy-Connection: Keep-Alive
  24. Cookie: ASPSESSIONIDAAAATBQC=FMEGGCKDBKHAMMCGKPFDMBFG; ASP.NET_SessionId=lusprmnom05lr445tmteaf55; userid=699879

 

以上为拦截内容,其中提交数据的参数部分(程序中的:strArgs)如:
__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=dDwtMTcwMzgxNjQ2Mjs7bDxDU
0ROVXNlckxvZ2luOmNiX1NhdmVTdGF0ZTtDU0ROVXNlckxvZ2luOkltYWdlX0xvZ2luOz4%2Btu
1q2wmRZoAJTi9L73w1zBleylY%3D&CSDNUserLogin%3Atb_UserName=testusername&CSDN
UserLogin%3Atb_Password=testpassword&CSDNUserLogin%3Atb_ExPwd=9232      


 
  1. protected static string cookieHeader;
  2. private void Page_Load(object sender, System.EventArgs e)
  3. {
  4. string strReContent = string.Empty;
  5. //登录
  6. strReContent = PostLogin("http://www.mystand.com.cn/login/submit.jsp提交的页面","提交的参数:userid=hgj0000&password=06045369","引用地址:http://www.mystand.com.cn/");
  7. //asp.net登录传递的参数需注意
  8. //strReContent = PostLogin("http://www.mystand.com.cn/login.aspx","__VIEWSTATE=dDwtNjkzMjUyNDczO3Q8O2w8aTwzPjs%2BO2w8dDxwPHA8bDxUZXh0Oz47bDxcZTs%2BPjs%2BOzs%2BOz4%2BOz6aX2dtqkJTK%2BKbNPsjd7Op%2Fl26Iw%3D%3D&txtUserName=hxf&txtPassword=hxf0000&btnEnter=%E7%99%BB%E5%BD%95","http://www.mystand.com.cn/login.aspx");
  9. //获取页面
  10. strReContent = GetPage("http://www.mystand.com.cn/company/getdata.jsp?code=","引用地址:http://www.mystand.com.cn/");
  11. //strReContent = GetPage("http://www.mystand.com.cn/Modules/index.aspx","http://www.mystand.com.cn/login.aspx");
  12. //可以对获得的内容进行处理:strReContent
  13. }
  14.  
  15. /**//// <summary>
  16. /// 功能描述:模拟登录页面,提交登录数据进行登录,并记录Header中的cookie
  17. /// </summary>
  18. /// <param name="strURL">登录数据提交的页面地址</param>
  19. /// <param name="strArgs">用户登录数据</param>
  20. /// <param name="strReferer">引用地址</param>
  21. /// <returns>可以返回页面内容或不返回</returns>
  22. public static string PostLogin(string strURL,string strArgs,string strReferer)
  23. {
  24. string strResult = "";
  25. HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
  26. myHttpWebRequest.AllowAutoRedirect = true;
  27. myHttpWebRequest.KeepAlive = true;
  28. myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";
  29. myHttpWebRequest.Referer = strReferer;
  30.  
  31. myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";
  32. myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
  33. myHttpWebRequest.Method = "POST";
  34.  
  35. CookieCollection myCookies = null;
  36. CookieContainer myCookieContainer = new CookieContainer();
  37. myHttpWebRequest.CookieContainer = myCookieContainer;
  38.  
  39. Stream MyRequestStrearm = myHttpWebRequest.GetRequestStream();
  40. StreamWriter MyStreamWriter = new StreamWriter(MyRequestStrearm,Encoding.ASCII);
  41. //把数据写入HttpWebRequest的Request流
  42. MyStreamWriter.Write(strArgs);
  43. //关闭打开对象
  44. MyStreamWriter.Close();
  45. MyRequestStrearm.Close();
  46.  
  47. HttpWebResponse response = null;
  48. System.IO.StreamReader sr = null;
  49. response = (HttpWebResponse)myHttpWebRequest.GetResponse();
  50.  
  51. cookieHeader = myHttpWebRequest.CookieContainer.GetCookieHeader(new Uri(strURL));
  52. HttpContext.Current.Application.Lock();
  53. HttpContext.Current.Application["cookieHeader"] = cookieHeader;
  54. HttpContext.Current.Application.UnLock();
  55. myCookies = response.Cookies;
  56.  
  57. sr = new System.IO.StreamReader(response.GetResponseStream(),Encoding.GetEncoding("gb2312")); // //utf-8
  58. strResult = sr.ReadToEnd();
  59. return strResult;
  60. }
  61.  
  62. /**//// <summary>
  63. /// 功能描述:在PostLogin成功登录后记录下Headers中的cookie,然后获取此网站上其他页面的内容
  64. /// </summary>
  65. /// <param name="strURL">获取网站的某页面的地址</param>
  66. /// <param name="strReferer">引用的地址</param>
  67. /// <returns>返回页面内容</returns>
  68. public static string GetPage(string strURL,string strReferer)
  69. {
  70. string strResult = "";
  71. HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
  72. myHttpWebRequest.ContentType = "text/html";
  73. myHttpWebRequest.Method = "GET";
  74. myHttpWebRequest.Referer = strReferer;
  75. myHttpWebRequest.Headers.Add("cookie:"+ cookieHeader);
  76.  
  77. HttpWebResponse response = null;
  78. System.IO.StreamReader sr = null;
  79. response = (HttpWebResponse)myHttpWebRequest.GetResponse();
  80. sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312")); // //utf-8
  81. strResult = sr.ReadToEnd();
  82. return strResult;
  83. }

 

 

---

转载请注明本文标题和链接:《C# winform网页登录和POST提交信息的多种方法