gpt4 book ai didi

C# 使用 HTTPWebRequest 登录网站

转载 作者:行者123 更新时间:2023-12-04 00:08:17 27 4
gpt4 key购买 nike

我正在尝试登录此网站:https://lms.nust.edu.pk/portal/login/index.php这是我的代码:

   const string uri = "https://lms.nust.edu.pk/portal/login/index.php";
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri);
wr.KeepAlive = true;
wr.Method = "POST";
wr.AllowAutoRedirect = false;
wr.Proxy = p;
wr.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
wr.ContentType = "application/x-www-form-urlencoded";
wr.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36";
string pdata = "username=USERNAME&password=PASSWORD";
byte[] data = UTF8Encoding.UTF8.GetBytes(pdata);
wr.ContentLength = data.Length;
CookieContainer cookie = new CookieContainer();
wr.CookieContainer = cookie;
using (Stream poststream = wr.GetRequestStream())
{
poststream.Write(data, 0, data.Length);
}
HttpWebResponse wp = (HttpWebResponse)wr.GetResponse();
wr.CookieContainer.Add(wp.Cookies);

它不会越过登录页面。这就是我所知道的正在发生的事情。 wp.Cookies 中没有 cookie。我调试了代码,它告诉我,即使我指定了 uri 并设置了 AllowAutoRedirect=false,它也不会转到那个 uri 和另一个 url。我不知道为什么或如何。有人可以帮帮我吗?

最佳答案

这应该可以解决您的问题,或者至少为您指明正确的方向,您可能还想下载 Fiddler 以帮助调试 HttpRequests...

string param = "username=MyUserName&password=123456";
string url = "https://lms.nust.edu.pk/portal/login/index.php";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = param.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = new CookieContainer();

using (Stream stream = request.GetRequestStream())
{
byte[] paramAsBytes = Encoding.Default.GetBytes(param);
stream.Write(paramAsBytes, 0, paramAsBytes.Count());
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
foreach (var cookie in response.Cookies)
{
var properties = cookie.GetType()
.GetProperties()
.Select(p => new
{
Name = p.Name,
Value = p.GetValue(cookie)
});

foreach (var property in properties)
{
Console.WriteLine ("{0}: {1}", property.Name, property.Value);
}
}
}

我得到的回应是……

Comment: 
CommentUri:
HttpOnly: False
Discard: False
Domain: lms.nust.edu.pk
Expired: False
Expires: 01/01/0001 00:00:00
Name: MoodleSession
Path: /
Port:
Secure: False
TimeStamp: 31/10/2014 00:13:58
Value: f6ich1aa2udb3o24dtnluomtd3
Version: 0

所以cookies肯定也会被退回......

关于C# 使用 HTTPWebRequest 登录网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665911/

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