我已尝试过多种方式以编程方式登录https网站,但我遇到了问题。每次我收到错误,说明我的登录名和密码不正确。我确信它们是正确的,因为我可以使用相同的凭据通过浏览器登录该站点。
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://www.majesticseo.com/account/login?EmailAddress=myemail&Password=mypass&RememberMe=1");
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,**;q=0.8";
request.UnsafeAuthenticatedConnectionSharing = true;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = true;
request.CookieContainer = container;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//String tmp;
foreach(Cookie cookie1 in response.Cookies)
{
container.Add(cookie1);
}
Stream stream = response.GetResponseStream();
string html = new StreamReader(stream).ReadToEnd();
Console.WriteLine("" + html);
答案 0 :(得分:1)
该网站使用HTTP POST进行登录,并且不会在URL中发送用户名和密码。
正确的登录网址为https://www.majesticseo.com/account/login
您需要创建一个要发布的数据字符串,将其转换为字节数组,设置内容长度然后执行您的请求。发送内容长度非常重要。如果没有它,帖子将无效。
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://www.majesticseo.com/account/login?EmailAddress=myemail&Password=mypass&RememberMe=1");
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0";
request.Referer = "https://www.majesticseo.com/account/login";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,**;q=0.8";
request.UnsafeAuthenticatedConnectionSharing = true;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = true;
// the post string for login form
string postData = "redirect=&EmailAddress=EMAIL&Password=PASS";
byte[] postBytes = System.Text.Encoding.ASCII.GetBytes(postData);
request.ContentLength = postBytes.Length;
System.IO.Stream str = request.GetRequestStream();
str.Write(postBytes, 0, postBytes.Length);
str.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.Stream stream = response.GetResponseStream();
string html = new System.IO.StreamReader(stream).ReadToEnd();
Console.WriteLine("" + html);
答案 1 :(得分:0)
您正在尝试发布某些内容(我没有看到,代码中有什么内容),但没有发布凭据。我想您的网页会显示一个网页表单,您可以在其中输入用户名(电子邮件地址?)和密码。然后浏览器发布此表单。因此,您需要复制浏览器行为 - 对表单内容进行编码并在发布请求中发送它们。对流行的浏览器使用一些网站管理员开发工具,以查看客户端浏览器向服务器发送的确切内容以及它如何对表单数据进行编码。接下来,您的请求很可能需要特殊的cookie,您可以通过访问另一个页面(例如登录页面)来收集这些cookie。发送预设的Cookie(就像您在评论代码中所做的那样)对大多数网站都不起作用。
换句话说,正确的机制是: