如何在 C# (.NET) 中使用 POST 变量登录 HTML 表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/524525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to login to HTML form using POST vars in C# (.NET)?
提问by Skuta
For example, there is this website: www.azet.sk
例如,有这个网站:www.azet.sk
On the right, there is login and password, I'd like my application to login to this web application and retrieve the data from my own account to C# (.NET) application and work with it. The aim is to keep the "logged in" connection alive and send vars using POST method. Is there any tutorial or easy script with examples to learn this?
在右侧,有登录名和密码,我希望我的应用程序登录到此 Web 应用程序并将数据从我自己的帐户检索到 C# (.NET) 应用程序并使用它。目的是保持“登录”连接处于活动状态并使用 POST 方法发送变量。是否有任何教程或带有示例的简单脚本来学习这个?
采纳答案by bleevo
string username = "your";
string password = "password";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://moje.azet.sk/prihlasenie.phtml?KDE=www.azet.sk%2Findex.phtml%3F");
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());
}
回答by Brannon
The login part should be relatively easy.
登录部分应该比较容易。
Use System.Net.WebClient
and the UploadValues()
method to POST the form data. Look at the HTML source to figure out the field values to POST.
使用System.Net.WebClient
和UploadValues()
POST 表单数据的方法。查看 HTML 源代码以找出要 POST 的字段值。
Most forms-based auth mechanisms use an HTTP cookie to keep the user logged in. So, after you POST the values, examine the WebClient
's ResponseHeaders
collection for the 'Set-Cookie:' header.
大多数基于表单的身份验证机制使用 HTTP cookie 来保持用户登录。因此,在您发布值后,检查'Set-Cookie:' 标头WebClient
的ResponseHeaders
集合。
Store the cookie value for subsequent GETs/POSTs to the website.
为网站的后续 GET/POST 存储 cookie 值。
You'll probably find that "retrieving the data from your account and working with it" is much more complicated (i.e. screen-scraping, etc).
您可能会发现“从您的帐户中检索数据并使用它”要复杂得多(即屏幕抓取等)。
Here's a link that has some examples:
这是一个包含一些示例的链接:
http://codebetter.com/blogs/brendan.tompkins/archive/2005/05/18/63329.aspx
http://codebetter.com/blogs/brendan.tompkins/archive/2005/05/18/63329.aspx
回答by tsilb
Look into the WebBrowser control. You can navigate anywhere and access the document and its controls programatically.
查看 WebBrowser 控件。您可以在任何地方导航并以编程方式访问文档及其控件。