HttpWebRequest, c# and Https

本文关键字:Https and HttpWebRequest | 更新日期: 2023-09-27 18:15:44

我尝试了很多方法登录到一个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);

HttpWebRequest, c# and Https

该站点使用HTTP POST登录,并且不发送URL中的用户名和密码。

正确的登录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);

您正在尝试发布一些东西(我看不到,什么,从您的代码),但不是凭据。我猜你的网页显示了一个网页表单,在那里你输入用户名(电子邮件地址?)和密码。然后浏览器发布这个表单。因此,您需要复制浏览器的行为-编码表单内容并在您的post请求中发送它们。使用一些流行浏览器的网站管理员开发工具来查看客户端浏览器发送给服务器的内容以及它如何对数据进行编码。接下来,你的请求很可能需要特殊的cookie,你可以通过访问另一个页面来收集。登录页面)。发送预设的cookie(就像你在注释代码中做的那样)对大多数站点不起作用。

换句话说,正确的机制是:

  1. 获取登录页面
  2. <
  3. 收集饼干/gh>
  4. POST表单数据并在请求中传递收集到的cookie。
  5. 收集其他可能在登录后发送的cookie。