模拟登陆求助
各位大神,http://www.36kr.com/,大家帮我看下这个网站该如何模拟登陆进去,第一个post总是302,该如何去模拟登陆进去呢?cookie都获取到了 模拟登陆,cookie
[解决办法]
/// <summary>
/// 第一次调用 先产生cookie
/// </summary>
/// <param name="strURL">路径</param>
/// <param name="strReferer">那个页面点击过去的</param>
/// <param name="charset">编码方式</param>
/// <returns></returns>
public string GetData(string strURL, string strReferer, string charset)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0";//这里模拟火狐浏览器。
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
//定义客户端可以处理的媒体类型,*/* 表示任何类型,type/* 表示该类型下的所有子类型。
request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";
// 请求方式get/post
request.Method = "GET";
//0xbb8十六进制 表示3秒的意思
request.Timeout = 0xbb8;
//表示由哪个页面点击过来的。
request.Referer = strReferer;
//if (System.Web.HttpContext.Current.Application["cookie"] != null)
//{
// cookieContainer = (CookieContainer)System.Web.HttpContext.Current.Application["cookie"];
//}
request.CookieContainer = cookieContainer;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
CookieCollection cookies = response.Cookies;
//System.Web.HttpContext.Current.Application["cookie"] = cookieContainer;
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(charset));
string str = reader.ReadToEnd();
reader.Close();
response.Close();
//
//CookieCollection c=cookieContainer.GetCookies(new Uri("http://91ka.com"));
return str;
}
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://www.36kr.com/account/sign_in");
CookieContainer cookie = new CookieContainer();
myReq.Accept = "*/*";
myReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon; .NET CLR 2.0.50727; .NET CLR 1.1.4322)";
myReq.Timeout = 7000;
myReq.AllowAutoRedirect = true;
myReq.Method = "GET";
myReq.Headers.Add("Accept-Language", "zh-cn");
myReq.MaximumAutomaticRedirections = 6;
myReq.ServicePoint.Expect100Continue = false;
myReq.ServicePoint.ConnectionLimit = 512;
HttpWebResponse res = GetResponse(myReq, cookie);
Stream rs = res.GetResponseStream();
string content = new StreamReader(rs, Encoding.UTF8).ReadToEnd();
rs.Close(); res.Close(); myReq.Abort();
private HttpWebResponse GetResponse(HttpWebRequest req,CookieContainer cookie)
{
try
{
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
cookie.GetCookies(req.RequestUri);
return res;
}
catch (Exception e)
{
req.Abort();
return null;
}
}