在此文档中,将介绍模拟提交程序相关的几个问题
登录主要使用了自动登录和提交post的方法
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"); //执行按扭操作
}
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.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("http://xxxxxxy.com.cn/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);
......
}
}
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();
// 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();
......
}
2.4.1 HttpWebRequest方法
string submitButton = "连接网络";
submitButton = System.Web.HttpUtility.UrlEncode(submitButto);
CookieContainer cc = new CookieContainer();
string postData = "DDDDD=" + this.txtuserName.Text + "&upass=" + this.txtpassword.Text + "&0MKKey" + submitButton; //+ "&0MKKey=%C1%AC%BD%D3%CD%F8%C2%E7";
byte[] byteArray = Encoding.Default.GetBytes(postData); // 转化
HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(new Uri("http://newlogin.bjut.edu.cn"));
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();
2.4.2 WebClient方法
要提交表单的URI字符串。
string uriString = "http://newlogin.bjut.edu.cn";
要提交的字符串数据。
string postString = "DDDDD=" + this.txtuserName.Text + "&upass=" + this.txtpassword.Text + "&0MKKey=" + submitButton;
初始化WebClient
WebClient webClient = new WebClient();
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
将字符串转换成字节数组
byte[] postData = Encoding.ASCII.GetBytes(postString);
上传数据,返回页面的字节数组
byte[] responseData = webClient.UploadData(uriString, "POST", postData);
返回的将字节数组转换成字符串(HTML)
string srcString = Encoding.Default.GetString(responseData);
注销只是固定的转到指定网页,因此只需转到那个网页即可
System.Diagnostics.Process.Start("IEXPLORE.EXE", "http://newlogin.bjut.edu.cn/F.htm");
将登录成功与失败的网页保存起来,再将用户登录时输入后服务器返回的页面也保存起来,比较两个文件的内容即可。比较两个文件内容不同的方法很多,比较两个文件的大小是一种很简单的方法
//保存返回的页面
HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.Default);
string text2 = sr2.ReadToEnd();
StreamWriter sww = new StreamWriter("C:\\result.html", false, Encoding.Default);
sww.Write(text2);
sww.Close();
sr2.Close();
//将登陆成功和失败的页面分别转换成两个字符串
StreamReader streamF = new StreamReader(Application.StartupPath + @"/fail.html", Encoding.Default);
string stringFail = streamF.ReadToEnd();
StreamReader streamS = new StreamReader(Application.StartupPath + @"/success.html", Encoding.Default);
string stringSuccess = streamS.ReadToEnd();
StreamReader streamR = new StreamReader("C:\\result.html", Encoding.Default);
string stringResult = streamR.ReadToEnd();
streamF.Close();
streamS.Close();
streamR.Close();
//登陆失败
if (stringResult.Length == stringFail.Length)
MessageBox.Show("帐号或密码不对,请重新输入");
//登陆成功
else if (stringResult.Length == stringSuccess.Length)
{
MessageBox.Show("您已经成功登录\n在完成工作后,请别忘记注销");
//若用户选择保存存储用户名和密码,修改配置文件
if (chkSave.Checked == true)
{
UpdateConfig("userName", txtuserName.Text);
UpdateConfig("password", txtpassword.Text);
}
}
//删除上面保存的网页
System.IO.File.Delete("C:\\result.html");
}
保存用户名和密码可以为方便用户使用,省去很多麻烦。可以用修改配置文件的方法来实现
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="userName" value=""/>
<add key="password" value=""/>
</appSettings>
</configuration>
private void Form1_Load(object sender, EventArgs e)
{
this.txtuserName.Text = ConfigurationSettings.AppSettings["userName"];
this.txtpassword.Text = ConfigurationSettings.AppSettings["password"];
}
/// 用来修改当前程序运行目录debug下的app.config文件
/// </summary>
/// <param name="strProgramName">string: 文件名</param>
/// <param name="strKey">string: config文件中的键名</param>
/// <param name="strValue">string: 相应的键值</param>
public void UpdateConfig(string strKey, string strValue)
{
// System.Reflection.Assembly ass = System.Reflection.Assembly.GetExecutingAssembly();
// string strFileName = ass.Location.Substring(0, (Asm.Location.LastIndexOf("\\") + 1) ) + strProgramName +".exe.config";
XmlDocument xmlDoc = new XmlDocument();
string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "loginnew.exe.config";
xmlDoc.Load(strFileName);
string xPath = @"//add[@key='" + strKey.Trim() + "']";
XmlNode node = xmlDoc.SelectSingleNode(xPath);
XmlElement ele = (XmlElement)node;
ele.SetAttribute("value", strValue);
xmlDoc.Save(strFileName);
}