C#网页自动登录和提交POST信息的多种方法 新人学习中

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

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

           HtmlElement ClickBtn =null;
           if (e.Url.ToString().ToLower().IndexOf("http://sandou.cnblogs.com/") > 0)   //登陆页面
            {
                HtmlDocument doc = webBrowser1.Document;
                for (int i = 0; i < doc.All.Count ; i++)
                {
                    if (doc.All[i].TagName.ToUpper().Equals("INPUT"))
                    {
                        switch (doc.All[i].Name)
                        {
                            case "userCtl":
                                doc.All[i].InnerText = "user01";
                                break;
                            case "passCt1":
                                doc.All[i].InnerText = "mypass";
                                break;
                            case "B1":
                                ClickBtn = doc.All[i]; //提交按钮
                                break;
                        }
                    }
                }
                ClickBtn.InvokeMember("Click");   //执行按扭操作
            }

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

 private void StartLoop(int ProxyNum)
        {
           WebClient []  wcArray = new WebClient[ProxyNum];  //初始化
             for (int idArray = 0; idArray< ProxyNum;idArray++)
            {
                 wcArray[idArray] = new WebClient();
                wcArray[idArray].OpenReadCompleted += new OpenReadCompletedEventHandler(Pic_OpenReadCompleted2);
                wcArray[idArray].UploadDataCompleted += new UploadDataCompletedEventHandler(Pic_UploadDataCompleted2);
                try
                {
                   
                    wcArray[idArray].Proxy = new WebProxy(proxy[1], port);
                    wcArray[idArray].OpenReadAsync(new Uri("http://sandou.cnblogs.com/")); //打开WEB;
                    proxy = null;
                }
                catch
                {
                }
            }
        }

        private void Pic_OpenReadCompleted2(object sender, OpenReadCompletedEventArgs e)
        {
                if (e.Error == null)
                {
                            string textData = new StreamReader(e.Result, Encoding.Default).ReadToEnd();  //取返回信息
                             ..
                              String cookie = ((WebClient)sender).ResponseHeaders["Set-Cookie"];
                             ((WebClient)sender).Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                            ((WebClient)sender).Headers.Add("Accept-Language", "zh-cn");
                            ((WebClient)sender).Headers.Add("Cookie", cookie);

                            string postData = ""
                            byte[] byteArray = Encoding.UTF8.GetBytes(postData); // 转化成二进制数组
                           ((WebClient)sender).UploadDataAsync(new Uri("http://sandou.cnblogs.com/"), "POST", byteArray);
                }
         }

        private void Pic_UploadDataCompleted2(object sender, UploadDataCompletedEventArgs e)
        {
                 if (e.Error == null)
                {
                    string returnMessage = Encoding.Default.GetString(e.Result);
                   
                }
       }

 


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

 
       private bool  PostWebRequest()       
        {
                   CookieContainer cc = new CookieContainer();
                    string pos tData = "user=" + strUser + "&pass=" + strPsd;
                    byte[] byteArray = Encoding.UTF8.GetBytes(postData); // 转化

                    HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(new Uri(http://sandou.cnblogs.com/));
                    webRequest2.CookieContainer = cc;
                    webRequest2.Method = "POST";
                    webRequest2.ContentType = "application/x-www-form-urlencoded";
                    webRequest2.ContentLength = byteArray.Length;
                    Stream newStream = webRequest2.GetRequestStream();
                    // Send the data.
                    newStream.Write(byteArray, 0, byteArray.Length);    //写入参数
                    newStream.Close();

                    HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
                    StreamReader sr2=new StreamReader(response2.GetResponseStream(), Encoding.Default);
                    string text2 =  sr2.ReadToEnd();
                 
        }    

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 的左侧栏的加号中依次点开,右边是它拦截到的内容:

 
POST http://www.csdn.net/member/UserLogin.aspx HTTP/1.0
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
Referer: http://www.csdn.net/member/UserLogin.aspx
Accept-Language: zh-cn
Content-Type: application/x-www-form-urlencoded
UA-CPU: x86
Pragma: no-cache
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; InfoPath.1)
Host: www.csdn.net
Content-Length: 355
Proxy-Connection: Keep-Alive
Cookie: ASPSESSIONIDAAAATBQC=FMEGGCKDBKHAMMCGKPFDMBFG; ASP.NET_SessionId=lusprmnom05lr445tmteaf55; userid=699879

__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
GET http://www.csdn.net/mycustompage.htm?aspxerrorpath=/member/UserLogin.aspx HTTP/1.0
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
Referer: http://www.csdn.net/member/UserLogin.aspx
Accept-Language: zh-cn
UA-CPU: x86
Pragma: no-cache
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; InfoPath.1)
Host: www.csdn.net
Proxy-Connection: Keep-Alive
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


 
        protected static string cookieHeader;
        private void Page_Load(object sender, System.EventArgs e)
        {
            string strReContent = string.Empty;
            //登录
            strReContent = PostLogin("http://www.mystand.com.cn/login/submit.jsp提交的页面","提交的参数:userid=hgj0000&password=06045369","引用地址:http://www.mystand.com.cn/");
            //asp.net登录传递的参数需注意   
            //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");
            //获取页面
            strReContent = GetPage("http://www.mystand.com.cn/company/getdata.jsp?code=","引用地址:http://www.mystand.com.cn/");
            //strReContent = GetPage("http://www.mystand.com.cn/Modules/index.aspx","http://www.mystand.com.cn/login.aspx");
            //可以对获得的内容进行处理:strReContent
        }

        /** <summary>
        /// 功能描述:模拟登录页面,提交登录数据进行登录,并记录Header中的cookie
        /// </summary>
        /// <param name="strURL">登录数据提交的页面地址</param>
        /// <param name="strArgs">用户登录数据</param>
        /// <param name="strReferer">引用地址</param>
        /// <returns>可以返回页面内容或不返回</returns>
        public static string PostLogin(string strURL,string strArgs,string strReferer)
        {
            string strResult = "";
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
            myHttpWebRequest.AllowAutoRedirect = true;
            myHttpWebRequest.KeepAlive = true;
            myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";
            myHttpWebRequest.Referer = strReferer;
           
            myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";
            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            myHttpWebRequest.Method = "POST";

            CookieCollection myCookies = null;
            CookieContainer myCookieContainer = new CookieContainer();
            myHttpWebRequest.CookieContainer = myCookieContainer;

            Stream MyRequestStrearm = myHttpWebRequest.GetRequestStream();
            StreamWriter MyStreamWriter = new StreamWriter(MyRequestStrearm,Encoding.ASCII);
            //把数据写入HttpWebRequest的Request流
            MyStreamWriter.Write(strArgs);
            //关闭打开对象
            MyStreamWriter.Close();
            MyRequestStrearm.Close();

            HttpWebResponse response = null;
            System.IO.StreamReader sr = null;
            response = (HttpWebResponse)myHttpWebRequest.GetResponse();

            cookieHeader = myHttpWebRequest.CookieContainer.GetCookieHeader(new Uri(strURL));
            HttpContext.Current.Application.Lock();
            HttpContext.Current.Application["cookieHeader"] = cookieHeader;
            HttpContext.Current.Application.UnLock();
            myCookies = response.Cookies;

            sr = new System.IO.StreamReader(response.GetResponseStream(),Encoding.GetEncoding("gb2312"));    //    //utf-8
            strResult = sr.ReadToEnd();
            return strResult;
        }

        /** <summary>
        /// 功能描述:在PostLogin成功登录后记录下Headers中的cookie,然后获取此网站上其他页面的内容
        /// </summary>
        /// <param name="strURL">获取网站的某页面的地址</param>
        /// <param name="strReferer">引用的地址</param>
        /// <returns>返回页面内容</returns>
        public static string GetPage(string strURL,string strReferer)
        {
            string strResult = "";
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
            myHttpWebRequest.ContentType = "text/html";
            myHttpWebRequest.Method = "GET";
            myHttpWebRequest.Referer = strReferer;
            myHttpWebRequest.Headers.Add("cookie:"+ cookieHeader);

            HttpWebResponse response = null;
            System.IO.StreamReader sr = null;
            response = (HttpWebResponse)myHttpWebRequest.GetResponse();
            sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312"));    //    //utf-8
            strResult = sr.ReadToEnd();
            return strResult;
        }

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

未解决问题——目前最大问题无法绕过验证码——我曾经和同事讨论图片的算法,基本上很难识别,网上也有很多识别验证码的例子,但是对于简单的噪声还是可以的,可是对于复杂的就一点用都没有了!到目前为止,我没有测试成功过!如果你有测试成功过,请帖代码,我们一起研究研究。

转载于:https://www.cnblogs.com/gxy217/archive/2012/06/07/2539121.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/377462.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

四、采集和制作数据集

一、采集数据 安装labelme&#xff1a;pip install labelme 打开labelme&#xff1a;labelme 将收集好的照片(320320&#xff0c;png格式)存放到一个文件夹中&#xff0c;例如我的是F:\test&#xff0c;再此文件夹下再创建个文件夹label用于存放标签文件 使用labelme打开数据…

MTFBWU的完整形式是什么?

MTFBWU&#xff1a;愿力量与您同在 (MTFBWU: May The Force Be With You) MTFBWU is an abbreviation of “May The Force Be With You". MTFBWU是“愿力量与你同在”的缩写 。 It is an expression, which is commonly used in messaging or chatting on social media n…

VMware14.0 安装 CentOS7.2

大致流程 对于VMware14.0安装包用百度网盘下载即可。 链接&#xff1a;https://pan.baidu.com/s/1DEGa47EbI1Fup_MTXhv0xg 提取码&#xff1a;izo6 华为云CentOS7 下载划线的。其他步骤与大致流程里一样。 最后输入root 以及配置的密码即可&#xff1a;密码输入时是没有任何显…

基于visual Studio2013解决C语言竞赛题之1049抓牌排序

&#xfeff;&#xfeff;&#xfeff;&#xfeff;&#xfeff;&#xfeff;题目解决代码及点评/* 功能&#xff1a;插入排序。许多玩牌的人是以这样的方式来对他们手中的牌进行排序的&#xff1a;设手中原有3张牌已排好序&#xff0c;抓1张新牌&#xff0c;若这张新牌的次序在…

学习Lucene笔记一:创建索引

public class HelloLucene {/*** 建立索引* param args*/public void index(){IndexWriter writer null; try {//1.创建Directory,// Directory directory new RAMDirectory();//索引是建立在内存中的Directory directory FSDirectory.open(new File("D:/Lucene/ind…

【C++进阶】C++创建文件/屏幕输出流类(将信息同时输出到文件和屏幕)

在软件的调试技术中&#xff0c;很重要的一个技术是将软件运行过程中的一些信息写入到“日志文件”中。但是同时还要将信息显示到屏幕上&#xff0c;以方便程序员实时查看这些信息。 最简单的一种办法是这样的&#xff1a; std::ofstream output("debug.log", ios::…

五、加载数据集

之前写过加载数据集的一些小笔记&#xff0c;这里详细内容就不再叙述了 详细学习可以参考该博文二、PyTorch加载数据 一、分析 因为U-net网络架构是输入1通道&#xff0c;大小为(572,572)的灰度图&#xff0c;图片大小无所谓&#xff0c;我的思路是将三通道的图像使用OpenCV进…

CDMA的完整形式是什么?

CDMA&#xff1a;码分多址 (CDMA: Code Division Multiple Access) CDMA is an abbreviation of Code Division Multiple Access. Code Division Multiple Access is a digital cellular technology and displays a network of multiple accesses. The various radio communica…

BCD码与十进制的相互转换

BCD码是用每四位代替一位十进制数&#xff08;0 到 9 的某一位数&#xff09; 例如&#xff1a;0x25 就代表25 十六进制的每位转换成二进制代表四个位。 下面是bcd转char short int long c语言程序 //************************************************************…

DSP关于存储器读写、IO读写时序图的注意点

这里的存储器图不涉及插入等待周期。 IO设备的图可以自行减去插入等待周期&#xff0c;然后观察。 存储器读读写 存储器写写读 I/O设备读写操作

折腾430 launchpad

launchpad到手也已经很长时间了&#xff0c;团购了一个g2的&#xff0c;一个铁电的&#xff0c;现在马上又要来一个g2的&#xff0c;感觉手上的东西太多了&#xff0c;急需消化一下&#xff0c;首先呢还是先把430搞定吧。 ---------------------------------------------------…

oem模式是什么_OEM的完整形式是什么?

oem模式是什么OEM&#xff1a;原始设备制造商 (OEM: Original Equipment Manufacturer) OEM is an abbreviation of "Original Equipment Manufacturer". Its meaning has changed over time. In former times, it alluded to a corporation that manufactures produ…

妈了个巴卡

配置文件修改&#xff1a; 一、打开PC端微信&#xff0c;打开咩了个咩小程序&#xff0c;点进入第一关&#xff0c;之后再关掉小程序 二、PC端微信设置里面&#xff0c;找到管理文件&#xff0c;打开文件夹 三、Applet下按修改日期找到a9结尾的文件 四、接着进入\usr\gamecac…

java中Iterator的小程序

import java.util.Collection; import java.util.HashSet; import java.util.Iterator;public class TestIterator {public static void main(String[] args){Collection booksnew HashSet();books.add("java讲义");books.add("java的Ajax宝典");books.add…

【C++进阶】利用重载二元运算符改进平面向量类Vec2D

先前回顾 在【C进阶】 遵循TDD原则&#xff0c;实现平面向量类(Vec2D)中我们初步实现了Vec2D内容&#xff0c;现在做出一定的改进&#xff1a; 实现Vec2D的一半二元算数运算符重载 1、 - (两个Vec2D对象运算以及1个Vec2D对象与一个double数运算) 2、*(点乘和数乘) 同时将之前…

在SQL中使用DEFAULT约束

DEFAULT constraint is used to insert default value into a column on a table and if no any value is stored in any place of a column then default value will be added into it. DEFAULT约束用于将默认值插入到表的列中&#xff0c;如果列的任何位置均未存储任何值&…

(ios7) 解决代码布局View, ios7 中 subView 高度增加StatusBar20dp的问题,保证Ios6,ios7代码一致...

在ios7 布局中&#xff0c;Status Bar 和 ToolBar &#xff0c;NavigateBar 等都包含在ViewControl的主View中。 这样原来ios6 的View布局 整体向上移动了20dp&#xff0c;下面是保证ios6,ios7代码一致的解决方案 1 第一步 在项目的Info.plist 文件中 添加一行属性配置 View co…

简单的群体测试方案C++代码(Group testing against Covid-19)

原理参考链接 https://www.econstor.eu/handle/10419/221811 http://www.magigen.com/h-nd-348.html 文章原理回顾 文章比较了两种估计人群中病毒流行率的方法&#xff1a; 1、个体测试&#xff0c;即对12000人的样本进行病毒测试&#xff0c;并采用标准二项测试得出95%的置…

使用WinDbg和VMware调试NDIS中间层驱动程序 (转)

使用WinDbg和VMware调试NDIS中间层驱动程序 我这里将一步一步的介绍&#xff0c;是从新手的角度来讲的&#xff0c;所以对高手来说&#xff0c;可能有些啰嗦。如果你看完这篇文章还不知道如何设置&#xff0c;那么原因可能有两个&#xff1a;1. 我没讲好&#xff1b;2. 你需要稍…

c语言字符常量和字符串常量_C语言中的字符常量

c语言字符常量和字符串常量Any character (a single character) that is enclosed within the single quotes (like, A) is called character constants in C programming language. 用单引号引起来的任何字符(单个字符)(例如A ) 在C编程语言中称为字符常量 。 Character cons…