views:

155

answers:

1

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.

+10  A: 

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));
consultutah
Execute that code too many times with the wrong credentials and pretty surely the user will be locked out of his account.
Jeroen
but how could i know that user logged in successfully in the code.... ?could it be done through through HTTP Request ? (i think it is good for the beginner like me)Thnks in anticipation !!!
xtremist
With Watin, you would then check browser.ContainsText("Welcome [email protected]!") or something along those lines. You absolutely could do it with HttpWebRequest, but the code is much more difficult. I'll edit my answer and add the code above.
consultutah
I won't do it for you - I don't want to be accused of hacking into their site. But I can tell you that all 3 work fine. I'd delete the comment with your login info if I were you.
consultutah
@consultutah, thanks for your great help !!!i have deleted my last request as suggested by you ... basically i just want to get out of this situation :( i have already wasted too much time on this but all in vain .... Anyway thanks once again consultutah
xtremist