C#HttpWebRequest使用
求一个先一个网页提交数据的实例!用来模拟登录!可以加分
求一个先一个网页提交数据的实例!用来模拟登录!可以加分
答案: private bool AutoLogon(string userId, string password)
{try
{
#region 获取登录FORM的输入框 和 Submit 按钮
HtmlElement textboxUserId = this.webBrowser1.Document.GetElementById("username");
//如果没有ID,用 Name 获取
//HtmlElement textboxUserId = this.webBrowser1.Document.All["登录用户名文本框的Name"];
HtmlElement textboxPassword = this.webBrowser1.Document.GetElementById("password3");
//如果没有ID, 用Name 获取
//HtmlElement textboxPassword = this.webBrowser1.Document.All["登录密码框的Name"];
// HtmlElement buttonSubmit = this.webBrowser1.Document.GetElementById("登录按钮的ID");
//如果没有ID, 用Name获取
//HtmlElement buttonSubmit = this.webBrowser1.Document.All["登录按钮的Name"];
textboxUserId.SetAttribute("value", userId); //填写帐号
textboxPassword.SetAttribute("value", password); //填写密码
// buttonSubmit.InvokeMember("click"); //触发提交按钮的点击事件
//当然,登录,也可以用
HtmlElement btn = this.webBrowser1.Document.GetElementById("login");
btn.InvokeMember("click");
#endregion
string html = this.webBrowser1.Document.Body.InnerHtml;
if (!string.IsNullOrEmpty(html))
{
return true;
}
}
catch (Exception)
{
return false;
}
return false;//登录后,需判断登录是否成功, 可以根据登录后的 URL
//或者 this.webBrowser1.Document.Body.InnerHtml的内容来判断
}请参考csdn的一个做法:
http://blog.csdn.net/vip__888/article/details/5646260
c# 使用 HttpWebRequest模拟登陆(附带验证码)
关于你提到的C#HttpWebRequest使用这个问题,,建议你去北风网看一下他们的.net课程,也许有老师讲的课有解决这方面问题的。希望可以帮助到你。
我给你找了参考资料链接: http://www.ibeifeng.com/goods.php?id=56
这个通过微软的帮助就有了,多按f1路过,
/// <summary>
/// 发送数据到指定URL
/// </summary>
/// <param name="mycookie">cookie容器</param>
/// <param name="url">要发送到的地址</param>
/// <param name="s">要发送的内容</param>
/// <param name="encode">要发送的内容编码</param>
/// <param name="result">是否成功 </param>
/// <returns></returns>
public static bool SendData(CookieContainer MyCookie, string url, string s, string code)
{
bool result = false;
string str = "";
Encoding encode = System.Text.Encoding.GetEncoding(code);
byte[] arrB = encode.GetBytes(s);
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.Method = "POST";
myReq.Timeout = 5000;
myReq.CookieContainer = MyCookie;
myReq.ContentType = "application/x-www-form-urlencoded";
myReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";
myReq.ContentLength = arrB.Length;
try
{
Stream outStream = myReq.GetRequestStream();
outStream.Write(arrB, 0, arrB.Length);
outStream.Close();
result = true;
}
catch
{
result = false;
}
return result;
}
//调用方式
CookieContainer cookie=new CookieContainer(); //uhtml为用户名HTML的name,Phtml为密码的HTML的name,最后一个参数为编码
//result为true表示登陆成功
bool result = Html.SendData(cookie, 登陆网址, uhtml+"=" + userid + "&"+phtml+"=" + password, "utf-8");