打开登录页面,插入的登录信息,然后单击loginbutton
问题描述:
我想开一个登录页面,就像www.site.com/login.php打开登录页面,插入的登录信息,然后单击loginbutton
插入用户名和密码
和登录按钮来调用。
所有这一切都应该在progroamlly(不是在一个浏览器)
的服务器做的是有可能这样做thsi?
答
你必须保持之间的CookieContainer实例。如果你想以登录用户的身份触发请求,登录POST请求(可能会设置登录cookie)和进一步请求。
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。
答
您可以对登录按钮提交的任何位置执行POST请求。 只需在请求中传递用户名和密码即可。
答
每次登录页面往往都是这种格式:
<form action="login.extention" method="post or get">
<input name="username" type="text" />
<input name="password" type="password" />
</form>
您必须获取或邮寄您的信息的操作页面(通常是POST)
答
我也做了同样的小项目
我添加超链接在.aspx页面中的一个,点击它会自动登录我到外部网站
上的Page_Load后调用下面的代码
HyperLink1.NavigateUrl = "javascript:__doExternalPost(\"http://www.xyz.com/login.jsp\");";
if (Page.IsPostBack == false)
{
this.Page.ClientScript.RegisterHiddenField("username", USERNAME);
this.Page.ClientScript.RegisterHiddenField("password", PASSWORD);
}
在.aspx页面中
添加以下JavaScript
function __doExternalPost(targetUrl)
{
theForm.__VIEWSTATE.value = "";
theForm.encoding = "application/x-www-form-urlencoded";
theForm.action = targetUrl;
theForm.target = "_blank";
theForm.submit();
}
希望它能帮到你
这样做的目的是让ASP.NET站点自动登录到另一个基于PHP的站点? – tjrobinson 2011-05-20 09:48:15
是的,如果可能的话,我想在登录后下载文件。 – Ata 2011-05-20 10:06:14