本帖最后由 阿童木最爱喵了 于 2014-5-27 22:08 编辑
[C#] 纯文本查看 复制代码 //使用URLEncode是为了解决中文用户名或者密码的问题
public static string URLDecode(string text)
{
return HttpUtility.UrlDecode(text, Encoding.GetEncoding("utf-8"));
}
public static string URLEncode(string text)
{
return HttpUtility.UrlEncode(text, Encoding.GetEncoding("utf-8"));
}
第一次HTTP:提取formhash
[C#] 纯文本查看 复制代码 //第一次HTTP:提取formhash
string formhash = "";
HttpHelper http = new HttpHelper();
HttpItem item = new HttpItem()
{
URL = "http://www.gamemake.org/member.php?mod=logging&action=login",//URL 必需项
Encoding = System.Text.Encoding.GetEncoding("utf-8"),
Method = "Get",//URL 可选项 默认为Get
Cookie = "",//字符串Cookie 可选项
UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",//用户的浏览器类型
ContentType = "text/html"//返回类型 可选项有默认值
};
HttpResult result = http.GetHtml(item);
//提取COOKIE
string cookie = result.Cookie.Replace("path=/;", "");
//提取formhash
formhash = Regex.Match(result.Html, @"(?<=formhash=)\w+").Value;
第二次HTTP:获取COOKIE
[C#] 纯文本查看 复制代码 //第二次HTTP:获取COOKIE
item=new HttpItem()
{
URL = "http://www.gamemake.org/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=Ld7k8&inajax=1",//URL 必需项
Encoding = System.Text.Encoding.GetEncoding("utf-8"),
Method = "Post",// 可选项 默认为Get
Cookie = cookie,//字符串Cookie 直接用第一次GET到的cookie
Referer = "http://www.gamemake.org/member.php?mod=logging&action=login",//来源URL 可选项
Postdata = "formhash=" + formhash + "&referer=http%3A%2F%2Fwww.gamemake.org%2F.%2F&loginfield=username&username=" + URLEncode(textBox1.Text.Trim()) + "&password=" + URLEncode(textBox2.Text.Trim()) + "&questionid=0&answer=",//Post数据
UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT6.0)",//用户的浏览器类型
ContentType = "application/x-www-form-urlencoded"//返回类型 可选项有默认值
};
result = http.GetHtml(item);
//提取COOKIE
cookie = result.Cookie;//.Replace("path=/,", "").Replace("path=/;", "").Replace("path=/", "");
点击登录后的执行结果:
说明登陆成功了,并存储此时的COOKIE。
第三次HTTP请求,点击按钮“验证”,使用的COOKIE是登录成功时返回的COOKIE,GET论坛主页,结果提示未登录的HTML。
此时捕获的COOKIE也是未登录时所返回的一般COOKIE。
下面是代码
[C#] 纯文本查看 复制代码 //第三次HTTP,用于验证
item = new HttpItem()
{
URL = "http://www.gamemake.org",//URL 必需项
Encoding = System.Text.Encoding.GetEncoding("utf-8"),
Referer = "http://www.gamemake.org/member.php?mod=logging&action=login",//来源URL
UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT6.0)",//用户的浏览器类型
ContentType = "application/x-www-form-urlencoded",//返回类型 可选项有默认值
Cookie = cookie//字符串Cookie
};
result = http.GetHtml(item);
//显示结果
richTextBox1.Text = result.Cookie.Replace("path=/,", "").Replace("path=/;", "").Replace("path=/", "");
感谢你,愿意花时间读完我的疑问!
|