C#模拟登录总结
C#模拟登录总结
/**//// <summary> 登录
/// </summary>
/// <param name="url"></param>
/// <param name="paramList"></param>
/// <returns></returns>
public static string Login(String url, String paramList)
{
HttpWebResponse res = null;
string strResult = "";
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.AllowAutoRedirect = false;
CookieContainer cookieCon = new CookieContainer();
req.CookieContainer = cookieCon;
StringBuilder UrlEncoded = new StringBuilder();
Char[] reserved = { '?', '=', '&' };
byte[] SomeBytes = null;
if (paramList != null)
{
int i = 0, j;
while (i < paramList.Length)
{
j = paramList.IndexOfAny(reserved, i);
if (j == -1)
{
UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length - i)));
break;
}
UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j - i)));
UrlEncoded.Append(paramList.Substring(j, 1));
i = j + 1;
}
SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());
req.ContentLength = SomeBytes.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
}
else
{
req.ContentLength = 0;
}
res = (HttpWebResponse)req.GetResponse();
cookieheader = req.CookieContainer.GetCookieHeader(new Uri(url));
Stream ReceiveStream = res.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("GBK");
StreamReader sr = new StreamReader(ReceiveStream, encode);
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
strResult += str;
count = sr.Read(read, 0, 256);
}
}
catch (Exception e)
{
strResult = e.ToString();
}
finally
{
if (res != null)
{
res.Close();
}
}
return strResult;
}
/**//// <summary> 获取页面HTML
/// </summary>
/// <param name="url"></param>
/// <param name="paramList"></param>
/// <returns></returns>
public static string getPage(String url, String paramList)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Headers["If-None-Match"] = "36d0ed736e88c71:d9f";
req.Referer = "http://website/login.do";
CookieContainer cookieCon = new CookieContainer();
req.CookieContainer = cookieCon;
req.CookieContainer.SetCookies(new Uri(url), cookieheader);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream(),Encoding.Default);
string strResult = sr.ReadToEnd();
sr.Close();
return strResult;
}调用:
string postData = "userName=admin&password=pass&area=2006&Submit=%B5%C7+%C2%BC";
string strLogin, strResult;
strLogin = Login("http://website/login.do", postData);
strResult = getPage("http://website/tohjtree.do", "");
//输出
this.webBrowser1.Document.Write(strResult);
C#(WINFORM)实现模拟POST发送请求登录网站
作者:不详 来源:vscodes.com整理 发布时间:2007-8-5 14:29:24 发布人:Polaris
减小字体 增大字体
最近接了个小项目,用到一个技术需要模拟POST向Web服务器发送请求来进行登录,下面写一下主要代码。
string strId = "admin";//用户名
string strPassword = "xxxxx";//密码
//string strsubmit = "YES";
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=" + strId;
postData += ("&password=" + strPassword);
//postData += ("&Accept=" + strsubmit);
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www.csharpcn.com/login.aspx");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
// Get response
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
string content = reader.ReadToEnd();
//Response.Write(content);
textBox1.Text = content;
通过HttpWebRequest 发送 POST 请求实现自动登陆[ 2006-09-15 16:17:12 | 作者: 景裔 ]
字体大小: 大 | 中 | 小
怎样通过HttpWebRequest 发送 POST 请求到一个网页服务器?例如编写个程序实现自动用户登录,自动提交表单数据到网站等。
假如某个页面有个如下的表单(Form):view plaincopy to clipboardprint?
<form name="form1" action="http:www.breakn.com/login.asp" method="post">
<input type="text" name="userid" value="">
<input type="password" name="password" value="">
</form>
<form name="form1" action="http:www.breakn.com/login.asp" method="post">
<input type="text" name="userid" value="">
<input type="password" name="password" value="">
</form>从表单可看到表单有两个表单域,一个是userid另一个是password,所以以POST形式提交的数据应该包含有这两项。
其中POST的数据格式为:
表单域名称1=值1&表单域名称2=值2&表单域名称3=值3……
要注意的是“值”必须是经过HTMLEncode的,即不能包含“<>=&”这些符号。
本例子要提交的数据应该是:
userid=value1&password=value2
用C#写提交程序:view plaincopy to clipboardprint?
string strId = "guest";
string strPassword= "123456";
ASCIIEncoding encoding=new ASCIIEncoding();
string postData="userid="+strId;
postData += ("&password="+strPassword);
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http:www.here.com/login.asp");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
// Get response
HttpWebResponse myResponse=(HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.Default);
string content = reader.ReadToEnd();
Console.WriteLine(content);
string strId = "guest";
string strPassword= "123456";
ASCIIEncoding encoding=new ASCIIEncoding();
string postData="userid="+strId;
postData += ("&password="+strPassword);
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http:www.here.com/login.asp");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
// Get response
HttpWebResponse myResponse=(HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.Default);
string content = reader.ReadToEnd();
Console.WriteLine(content);
protected static string cookieHeader;
private void Page_Load(object sender, System.EventArgs e)
{
string strReContent = string.Empty;
//登录
strReContent = PostLogin("http://www.mystand.com.cn/login/submit.jsp提交的页面","提交的参数:userid=hgj0000&password=06045369","引用地址:http://www.mystand.com.cn/");
//asp.net登录传递的参数需注意
//strReContent = PostLogin("http://www.mystand.com.cn/login.aspx","__VIEWSTATE=dDwtNjkzMjUyNDczO3Q8O2w8aTwzPjs%2BO2w8dDxwPHA8bDxUZXh0Oz47bDxcZTs%2BPjs%2BOzs%2BOz4%2BOz6aX2dtqkJTK%2BKbNPsjd7Op%2Fl26Iw%3D%3D&txtUserName=hxf&txtPassword=hxf0000&btnEnter=%E7%99%BB%E5%BD%95","http://www.mystand.com.cn/login.aspx");
//获取页面
strReContent = GetPage("http://www.mystand.com.cn/company/getdata.jsp?code=","引用地址:http://www.mystand.com.cn/");
//strReContent = GetPage("http://www.mystand.com.cn/Modules/index.aspx","http://www.mystand.com.cn/login.aspx");
//可以对获得的内容进行处理:strReContent
}
/**//// <summary>
/// 功能描述:模拟登录页面,提交登录数据进行登录,并记录Header中的cookie
/// </summary>
/// <param name="strURL">登录数据提交的页面地址</param>
/// <param name="strArgs">用户登录数据</param>
/// <param name="strReferer">引用地址</param>
/// <returns>可以返回页面内容或不返回</returns>
public static string PostLogin(string strURL,string strArgs,string strReferer)
{
string strResult = "";
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
myHttpWebRequest.AllowAutoRedirect = true;
myHttpWebRequest.KeepAlive = true;
myHttpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";
myHttpWebRequest.Referer = strReferer;
myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
myHttpWebRequest.Method = "POST";
CookieCollection myCookies = null;
CookieContainer myCookieContainer = new CookieContainer();
myHttpWebRequest.CookieContainer = myCookieContainer;
Stream MyRequestStrearm = myHttpWebRequest.GetRequestStream();
StreamWriter MyStreamWriter = new StreamWriter(MyRequestStrearm,Encoding.ASCII);
//把数据写入HttpWebRequest的Request流
MyStreamWriter.Write(strArgs);
//关闭打开对象
MyStreamWriter.Close();
MyRequestStrearm.Close();
HttpWebResponse response = null;
System.IO.StreamReader sr = null;
response = (HttpWebResponse)myHttpWebRequest.GetResponse();
cookieHeader = myHttpWebRequest.CookieContainer.GetCookieHeader(new Uri(strURL));
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["cookieHeader"] = cookieHeader;
HttpContext.Current.Application.UnLock();
myCookies = response.Cookies;
sr = new System.IO.StreamReader(response.GetResponseStream(),Encoding.GetEncoding("gb2312")); // //utf-8
strResult = sr.ReadToEnd();
return strResult;
}
/**//// <summary>
/// 功能描述:在PostLogin成功登录后记录下Headers中的cookie,然后获取此网站上其他页面的内容
/// </summary>
/// <param name="strURL">获取网站的某页面的地址</param>
/// <param name="strReferer">引用的地址</param>
/// <returns>返回页面内容</returns>
public static string GetPage(string strURL,string strReferer)
{
string strResult = "";
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
myHttpWebRequest.ContentType = "text/html";
myHttpWebRequest.Method = "GET";
myHttpWebRequest.Referer = strReferer;
myHttpWebRequest.Headers.Add("cookie:"+ cookieHeader);
HttpWebResponse response = null;
System.IO.StreamReader sr = null;
response = (HttpWebResponse)myHttpWebRequest.GetResponse();
sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312")); // //utf-8
strResult = sr.ReadToEnd();
return strResult;
}
C#三种模拟自动登录和提交POST信息的实现方法
上一篇 / 下一篇 2008-03-21 11:07:20 / 个人分类:转载
查看( 80 ) / 评论( 0 ) / 评分( 0 / 0 )
转自:随风技术中心
在实际编程过程中,我们经常会遇到验证身份、程序升级网络投票会员模拟登陆等需要,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); // 转化免费资源http://www.it55.com
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();
......
}