HttpWebRequest 到 HTTPS 站点并重定向
我正在尝试使用 HttpWebRequest 自动从 HTTPS 页面读取一些信息。我请求的链接通常会重定向到一个具有登录/密码字段的页面,这些字段会发布到 php 文件。
我的代码不起作用,因为我只是取回包含带有用户名/密码字段的表单的页面信息。
我不确定应该如何处理这种情况。
一如既往地非常感谢任何帮助。
提前致谢。
NetworkCredential nc = new NetworkCredential(username, password);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://myaccount.talktalk.co.uk/myservices/bbusage/viewbbusage");
request.AllowAutoRedirect = true;
request.Credentials = nc;
request.Method = "POST";
CookieContainer cc = new CookieContainer();
request.CookieContainer = cc;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
I'm trying to automate the reading of some information from an HTTPS page using HttpWebRequest. The link I'm requesting normally redirects to a page that has login/password fields which are POSTed to a php file.
The code I have isn't working in that I'm just getting back the page information containing the form with username/password fields.
I'm not sure how I should handle this scenario.
Any assistance as always hugely appreciated.
Thanks in advance.
NetworkCredential nc = new NetworkCredential(username, password);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://myaccount.talktalk.co.uk/myservices/bbusage/viewbbusage");
request.AllowAutoRedirect = true;
request.Credentials = nc;
request.Method = "POST";
CookieContainer cc = new CookieContainer();
request.CookieContainer = cc;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此行导致跳过重定向页面,因为 HttpRequest 在返回之前自动遵循重定向链接。如果您想检查重定向页面,请将此标志更改为 false。
编辑:
我可能误读了这个问题,如果您的意思是您正在尝试访问实际页面(而不是重定向或登录页面),那么您不应该使用 NetworkCredential。 NetworkCredential 仅适用于 Basic、Kerbos 和类似的基于浏览器的身份验证系统,PHP 站点使用基于表单的身份验证,这需要您执行 post 请求。
这种情况下的解决方案是获取登录表单,填写适当的字段并发布它,确保保持 cookie 完好无损,因为此时您的 cookie 容器应包含您的身份验证信息。
This line is causing the redirect page to be skipped, as the HttpRequest automatically follows the redirect link before returning. If you wish to examine the redirect page then change this flag to false.
EDIT:
I may have misread the question, if you meant that you are attempting to get to the actual page (not the redirect or login pages) then you shouldn't be using NetworkCredential. NetworkCredential only works for Basic, Kerbos, and similar browser based authentication systems, the PHP site uses form based authentication, which requires you to perform the post request.
The solution in this case is to Get the login form, fill in the appropriate fields and post it, being sure to keep the cookies in tact, as your cookie container should at that point contain your authentication information.