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 = "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("website/login.do", postData);
strResult = getPage("website/tohjtree.do", "");
//输出
this.webBrowser1.Document.Write(strResult);
C#(WINFORM)实现模拟POST发送请求登录网站
作者:不详 来源:vscodes整理 发布时间: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
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("www.csharpcn/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/login.asp" method="post">
<input type="text" name="userid" value="">
<input type="password" name="password" value="">
</form>
<form name="form1" action="http:www.breakn/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
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http:www.here/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
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http:www.here/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 co
okieHeader;
private void Page_Load(object sender, System.EventArgs e)
{
string strReContent = string.Empty;
//登录
strReContent = PostLogin("stand/login/submit.jsp提交的页面","提交的参数:userid=hgj0000&password=06045369","引用地址:stand/");
//asp登录传递的参数需注意
//strReContent = PostLogin("stand/login.aspx","__VIEWSTATE=dDwtNjkzMjUyNDczO3Q8O2w8aTwzPjs%2BO2w8dDxwPHA8bDxUZXh0Oz47bDxcZTs%2BPjs%2BOzs%2BOz4%2BOz6aX2dtqkJTK%2BKbNPsjd7Op%2Fl26Iw%3D%3D&txtUserName=hxf&txtPassword=hxf0000&btnEnter=%E7%99%BB%E5%BD%95","stand/login.aspx");
//获取页面
strReContent = GetPage("stand/company/getdata.jsp?code=","引用地址:
//strReContent = GetPage("stand/Modules/index.aspx","stand/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();
printform
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;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论