How does one log in to a website programmatically?
I just want to check that the provided username and password of a website is correct or not.
Thanks.
How does one log in to a website programmatically?
I just want to check that the provided username and password of a website is correct or not.
Thanks.
The easiest way to do this from .NET is Watin. You would do something like:
using (var browser = new IE("http://mysite.com"))
{
browser.TextField(Find.ByName("email")).TypeText("[email protected]");
browser.TextField(Find.ByName("password")).TypeText("password");
browser.Button(Find.ByName("login")).Click();
if (browser.ContainsText("Welcome [email protected]!"))
{
// Success
}
}
To do it with HttpWebRequest, you would:
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentLength = postContent.Length;
req.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(postContent);
}
using (var res = (HttpWebResponse)req.GetResponse())
{
_status = res.StatusCode;
using (var streamReader = new StreamReader(res.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
}
Just to add a 3rd way, you could also use WebClient:
var nvc = new NameValueCollection();
nvc.Add("email", "[email protected]");
nvc.Add("password", "password");
var wc = new WebClient();
byte[] responseArray = wc.UploadValues("http://mysite.com",nvc);
string responseText = Encoding.ASCII.GetString(responseArray));