gpt4 book ai didi

c# - HttpWebRequest、C# 和 Https

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:13 25 4
gpt4 key购买 nike

我尝试了很多方法以编程方式登录 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);

最佳答案

该站点使用 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);

关于c# - HttpWebRequest、C# 和 Https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8281324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com