C#網頁自動登入和提交POST資訊的多種方法

來源:互聯網
上載者:User
網頁自動登入(提交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("http://xxxx.com.cn/tp.aspId=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("http://xxxxxxy.com.cn/tp.aspId=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("http://www.xxxx.com/chk.asp"));
webRequest2.CookieContainer = cc;
webRequest2.Method = "POST";
webRequest2.ContentType = "application/x-www-form-urlencoded";
webRequest2.ContentLength = byteArray.Length;
Stream newStream = webRequest2.GetRequestStream();
//Sendthedata.
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同樣提供了非同步作業,有興趣的朋友自己查MSDN

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.