c# 模拟登录帐号登录网站得不到应该有的数据

songsz123 2015-03-18 04:51:20
c#模拟登录知乎:const string Url = @"http://www.zhihu.com/login";
处理的大概流程也知道,就是用程序模拟浏览器,发送request,然后得到response,继而得到相应的html数据进行分析。
网上看了好多,用起来感觉不是很适应,大多都是应用cookies获取,我想先不用太复杂,直接帐号密码登录获取页面就行了,最后获取的html保存为html后如下所示:


可实际上我想得到最终的html是这样的


我的代码
        public static string SendRequest()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
//CookieContainer cc = new CookieContainer();

//---simulate account:
request.Method = "POST";
//request.ContentType = "";
//request.CookieContainer = cc;
string data = "_xsrf:aaaanumber&" +
"email:my@mail.com&" +
"password:password&" +
"rememberme:y";
data = HttpUtility.UrlEncode(data);
byte[] postdata = Encoding.UTF8.GetBytes(data);
request.Credentials = CredentialCache.DefaultCredentials;
request.ContentLength = postdata.Length;
request.AllowAutoRedirect = false;
request.KeepAlive = true;

using (Stream stream = request.GetRequestStream())
{
stream.Write(postdata, 0, postdata.Length);
stream.Close();
}

HttpWebResponse res = (HttpWebResponse)request.GetResponse();
//res.Cookies = cc.GetCookies(request.RequestUri);

// return response;
string htmlData = string.Empty;
Stream datastream = res.GetResponseStream();
if (datastream != null)
{
var reader = new StreamReader(datastream);
htmlData = reader.ReadToEnd();
reader.Close();
datastream.Close();
}
res.Close();
return htmlData;

}
...全文
172 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
hubro 2015-03-19
  • 打赏
  • 举报
回复
1.首先你得了解HTTP协议,浏览器是怎么实现请求和接收的 2.了解COOKIE,SESSION是怎么回事 3.了解登录验证和上面有什么关系
feiyun0112 2015-03-19
  • 打赏
  • 举报
回复
你没传cookie,服务器找不到你的登录信息,当然跳转到登陆页面啦
泡泡龙 2015-03-19
  • 打赏
  • 举报
回复
不能上来就发post吧,先发个首页的get获取cookie
songsz123 2015-03-18
  • 打赏
  • 举报
回复
没人么。。。。。

110,502

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧