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

 在实际编程过程中,我们经常会遇到验证身份、程序升级网络投票会员模拟登陆等需要,C#给我们提供了以下的实现方法:
         网页自动登录和提交POST信息的核心就是分析网页的源代码(HTML),在C#中,可以用来提取网页HTML的组件比较多,常用的用WebBrowser、WebClient、HttpWebRequest这三个。以下就分别用这三种方法来实现:
       1、WebBrowser是个"迷你"浏览器,其特点是Post时不用关心Cookie、内置JS等问题, WebBrowser是VS2005新提供的组件(其实就是封装了IE接口),实现POST功能一般在webBrowser的DocumentCompleted中分析HtmlDocument 来实现,代码如下:

HtmlDocument doc = webBrowser2.Document;
            HtmlElement btn = null;
            foreach (HtmlElement em in doc.All)
            {
                if (em.Name == "username")
                {
                    em.SetAttribute("value", "name");
                }
                if (em.Name == "pwd")
                {
                    em.SetAttribute("value", "password");
                }
                if (em.Id == "submitBtn")
                {
                    btn = em;
                }
            }
            btn.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
                {
                    //goto:此处有待完善
                    //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();  //取返回信息 
                //goto:此处有待完善
                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);
                //goto:此处有待完善
            }
        }


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

 

SRWebClient类代码:

using System;
using System.IO;
using System.Net;
using System.Web;
using System.Windows.Forms;
public class SRWebClient
{
    CookieContainer cookie;
    public SRWebClient()
    {
        cookie = new CookieContainer();
    }
    /// <TgData> 
    /// <Alias>下载Web源代码</Alias> 
    /// </TgData> 
    public string DownloadHtml(string URL)
    {
        HttpWebRequest request = HttpWebRequest.Create(URL) as HttpWebRequest;
        request.CookieContainer = cookie;
        request.AllowAutoRedirect = false;
        WebResponse res = request.GetResponse();
        string r = "";
        StreamReader S1 = new StreamReader(res.GetResponseStream(), System.Text.Encoding.UTF8);
        try
        {
            r = S1.ReadToEnd();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            res.Close();
            S1.Close();
        }
        return r;
    }
    /// <TgData> 
    /// <Alias>下载文件</Alias> 
    /// </TgData> 
    public long DownloadFile(string FileURL, string FileSavePath)
    {
        long Filelength = 0;
        HttpWebRequest req = HttpWebRequest.Create(FileURL) as HttpWebRequest;
        req.CookieContainer = cookie;
        req.AllowAutoRedirect = true;
        HttpWebResponse res = req.GetResponse() as HttpWebResponse;
        System.IO.Stream stream = res.GetResponseStream();
        try
        {
            Filelength = res.ContentLength;
            byte[] b = new byte[512];
            int nReadSize = 0;
            nReadSize = stream.Read(b, 0, 512);
            System.IO.FileStream fs = System.IO.File.Create(FileSavePath);
            try
            {
                while (nReadSize > 0)
                {
                    fs.Write(b, 0, nReadSize);
                    nReadSize = stream.Read(b, 0, 512);
                }
            }
            finally
            {
                fs.Close();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            res.Close();
            stream.Close();
        }
        return Filelength;
    }
    /// <TgData> 
    /// <Alias>提交数据</Alias> 
    /// </TgData> 
    public void Request(string RequestPageURL, RequestData Data)
    {
        string StrUrl = RequestPageURL;
        HttpWebRequest request = HttpWebRequest.Create(StrUrl) as HttpWebRequest;
        HttpWebResponse response;
        string postdata = Data.GetData();
        request.Referer = RequestPageURL;
        request.AllowAutoRedirect = false;
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.01; Windows NT 5.0)";
        request.CookieContainer = cookie;
        Uri u = new Uri(StrUrl);
        if (postdata.Length > 0) //包含要提交的数据 就使用Post方式 
        {
            //作为表单请求 
            request.ContentType = "application/x-www-form-urlencoded";
            //方式就是Post 
            request.Method = "POST";
            //把提交的数据换成字节数组 
            Byte[] B = System.Text.Encoding.Default.GetBytes(postdata);
            request.ContentLength = B.Length;
            Stream SW = request.GetRequestStream(); //开始提交数据 
            SW.Write(B, 0, B.Length);
            SW.Close();
        }
        response = request.GetResponse() as HttpWebResponse;
        response.Close();
    }
}

RequestData类代码:

using System.Collections;
using System.IO;
public class RequestData
{
    ArrayList arr = new ArrayList();
    public RequestData()
    {
    }
    public string GetData()
    {
        string r = "";
        for (int i = 0; i < arr.Count; i++)
        {
            data d = (data)arr[i];
            if (r.Length > 0)
                r += "&";
            r += d.Field + "=" + d.Value;
        }
        return r;
    }
    public void AddField(string Field, string Value)
    {
        data a = new data();
        a.Field = Field;
        a.Value = Value;
        arr.Add(a);
    }
    struct data
    {
        public string Field, Value;
    }
}

测试代码:

public void testDownSEOrder()
        {
            RequestData data = new RequestData();
            data.AddField("name", "str");
            data.AddField("password", "str");
            SRWebClient web = new SRWebClient();
            web.Request("url", data);
            string s = web.DownloadHtml("url");
            textBox1.Text = s;
        } 


 



 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值