[保存]POST信息的实现方法汇总

C#三种模拟自动登录和提交POST信息的实现方法

在实际编程过程中,我们经常会遇到验证身份、程序升级网络投票会员模拟登陆等需要,C#给我们提供了以下的实现方法:
       网页自动登录和提交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("xxx.htm") > 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("/tp.asp?Id=129")); //打开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("/tp.asp?Id=129"), "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("/chk.asp"));
                    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();
                  ......
        }


-----------------------------------------------------------------------------------
http://www.cnblogs.com/ahjxxy/archive/2009/07/10/1520717.html
1、如何获得“打开网页出错”信息

 

DocumentCompleted事件中,判断Document.Url.AbsoluteUri中的"res://":标志即可(以前总用e.Url,怪不得总截取不到)

if (webBrowser1.Document.Url.AbsoluteUri.IndexOf("res://") > -1) //出错处理

{

webBrowser1.Navigate(e.Url);

return;

}

2、如何使用IHTMLDocument2MSHTML功能

VS2005中没有完全封装MSHTML中的功能,留了个DomDocument接口。直接引用Microsoft HTML Object Library类库后,就可以操作IHTMLDocument2等复杂的功能了。如:IHTMLDocument2 doc2 = (IHTMLDocument2)webBrowser1.Document.DomDocument;

3、如何提取网页中的图片,尤其是验证码图等以流方式返回的图片

很多网站一些图片是动态生成了,是从服务器以流方式一点点发过来再组装成图片的。不管是以什么方式,到了客户端,都是完整的。用WebBrowser的好处就在这里,只要管住最终结果就OK了。以下是得到网页上验证码的代码:

/// <summary>

///返回指定WebBrowser中图片<IMG></IMG>中的图内容

/// </summary>

/// <param name="WebCtl">WebBrowser控件</param>

/// <param name="ImgeTag">IMG元素</param>

/// <returns>IMG对象</returns>

private Image GetWebImage(WebBrowser WebCtl, HtmlElement ImgeTag)

{

HTMLDocument doc = (HTMLDocument)WebCtl.Document.DomDocument;

HTMLBody body = (HTMLBody)doc.body;

IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange();

IHTMLControlElement Img = (IHTMLControlElement)ImgeTag.DomElement; //图片地址

Image oldImage = Clipboard.GetImage();

rang.add(Img);

rang.execCommand("Copy", false, null); //拷贝到内存

Image numImage = Clipboard.GetImage(); //Clipboard中取图

Clipboard.SetImage(oldImage); //还原

return numImage;

}

4、如何屏蔽掉Alert()类型的弹出窗口

首先申明这不是技术,只是一种处理的技巧。网上查了很多数据,对于网页中弹出Alert()窗口不好屏蔽(尤其是Writer出来的)。我的方法是做两个EXE,一个为主程序.exe,一个Run.exe WebBrowser控件放在RUN.exe中,在主程序中通过Process调用RUN.exe,而用在执行完任务后,将RUN.exe杀掉(Kill),这时Alert窗口会自动关闭。我用这种技巧做了好了个投票机,可以安静的运行,还能回避Session处理等问题,也不会在桌面上留下一堆窗口。


posted @ 2009-07-31 21:28  gotolnc  阅读(483)  评论(0编辑  收藏  举报