C# 中带有 https 的 HttpWebRequest
这段代码不起作用; 它正在登录使用 https 协议的网站。 如何解决这个问题呢? 该代码随时随地停止在 GetRequestStream()
处,表示协议违反异常未处理。
string username = "user";
string password = "pass";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://moje.azet.sk/prihlasenie.phtml?KDE=www.azet.sk%2Findex.phtml%3F");
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";
Console.WriteLine(request.GetRequestStream());
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("nick=" + username + "&password=" + password);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Retrieve your cookie that id's your session
//response.Cookies
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
This piece of code doesn't work; it's logging in into website which is using https protocol. How to solve this problem? The code stops at GetRequestStream()
anytime anywhere saying that protocol violation exception is unhandled..
string username = "user";
string password = "pass";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://moje.azet.sk/prihlasenie.phtml?KDE=www.azet.sk%2Findex.phtml%3F");
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";
Console.WriteLine(request.GetRequestStream());
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("nick=" + username + "&password=" + password);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Retrieve your cookie that id's your session
//response.Cookies
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将请求方法设置为 post
在调用 GetRequestStream之前
Set request method to post, before calling GetRequestStream
like
我的猜测是,您遇到的问题是由于您正在执行 GET 请求而不是 POST 请求(就像其他人建议的那样)。 此外,我注意到该页面上密码字段的实际名称是“heslo”而不是“password”。 此拼写错误不会导致 Web 服务器不返回响应,但会导致其他问题,因为服务器正在查找要与密码值一起发布的特定变量名称。
My guess is that the issue you are experiencing is due to the fact (like others have advised) that you are doing a GET request instead of a POST request. Additionally, I noticed that the actual name for the password field on that page is "heslo" and not "password". This typo won't cause the web server to not return a response, but it will cause other issues since the server is looking for that specific variable name to be posted with the password value.
您可能还想事先计算出要发布的内容的总长度,并将其设置为请求的 ContentLength。 请参阅 MSDN :
You might also want to figure out the total length of what you're posting, beforehand, and set that as the ContentLength of the request. See MSDN:
这对我有用:
Here is what works for me: