我想打开一个登录页面,如www.site.com/login.php
插入用户名和密码
并调用登录按钮。
所有这些都应该在服务器中编程完成(而不是在浏览器中)。
有可能做到这一点吗?
发布于 2011-05-20 18:27:02
如果希望以登录用户的身份触发请求,则必须在登录POST请求(可能设置登录cookie)和其他请求之间保留一个CookieContainer实例。
var cookieJar = new CookieContainer();
var loginData = new Dictionary<string,string>() {
// be carefull to use the same keys/names as the login form
{ "username", "LightWing" },
{ "password", "l33tPwD" }
};
var request = (HttpWebRequest)WebRequest.Create("http://.../login.php");
request.CookieContainer = cookieJar;
request.AllowAutoRedirect = true;
request.Method = "POST";
// build the POST data
byte[] dataBuffer = Encoding.ASCII.GetBytes(string.Join("&", loginData.AllKeys.Select(x => string.Concat(HttpUtility.UrlEncode(x), "=", HttpUtility.UrlEncode(loginData[x])))));
request.ContentLength = dataBuffer.LongLength;
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(dataBuffer, 0, dataBuffer.Length);
requestStream.Flush();
}
var response = request.GetResponse();
using (var responseStream = response.GetResponseStream())
{
// do some reading if you want..
}
// now _cookieJar should contain the login cookie...
// you can trigger further requests as a logged in user:
request = (HttpWebRequest)WebRequest.Create("http://.../restrictedPage.php");
request.CookieContainer = cookieJar; // reuse them cookies!
request.AllowAutoRedirect = true;
request.Method = "GET";
var response = request.GetResponse();
using (var responseStream = response.GetResponseStream())
{
// read the restricted page response
}我还编写了一个简单的实用程序来帮助您抓取使用回发的Asp.net WebForms页。你可以在here上找到它。
发布于 2011-05-20 17:44:01
您可以对登录按钮提交的任何位置执行POST请求。只需在请求中传递用户名和密码即可。
发布于 2011-05-20 17:45:40
每个登录页面通常采用以下格式:
<form action="login.extention" method="post or get">
<input name="username" type="text" />
<input name="password" type="password" />
</form>您必须通过get或post将信息发送到操作页面。(通常是post)
https://stackoverflow.com/questions/6070034
复制相似问题