从过去的几天开始,我一直在尝试使用webclient和webrequest登录,但出于某种原因,它无法正常工作。下面是我用来登录的代码。
private class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient()
: this(new CookieContainer())
{ }
public CookieAwareWebClient(CookieContainer c)
{
this.CookieContainer = c;
}
public CookieContainer CookieContainer { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
var castRequest = request as HttpWebRequest;
if (castRequest != null)
{
castRequest.CookieContainer = this.CookieContainer;
}
return request;
}
}
下面是发布的html表单:
<form method="post" action="">
<div class="field">
<label>Email Address:</label>
<input type="text" value="" name="username">
<div class="clear"></div>
</div>
<div class="field">
<label>Password:</label>
<input type="password" name="password">
<div class="clear"></div>
</div>
<div class="field">
<div style="float:left; width:102px;height:20px; display:block;"> </div>
<a class="button_forgot_password_blue" href="/my-account/forgotten-password"></a>
<input type="submit" value="" class="button_login_blue" name="login">
<div class="clear"></div>
</div>
</form>
正如您所看到的,动作块完全是空的,我如何登录this.please help。
更新:这是我想要做的代码。
private void button1_Click(object sender, EventArgs e)
{
using (var client = new CookieAwareWebClient())
{
var values = new NameValueCollection
{
{ "username", "vallue" },
{ "password", "value" },
};
client.UploadValues("http://www.1stchoice.co.uk/my-account/sign-in", values);
// If the previous call succeeded we now have a valid authentication cookie
// so we could download the protected page
string result = client.DownloadString("http://www.1stchoice.co.uk/request/stop/7854140");
File.WriteAllText(@"c:\temp\clc.txt", result);
}
}