1

I'm trying to login to a website using C# and the WebRequest class. This is the code I wrote up last night to send POST data to a web page:

public string login(string URL, string postData)
{
    Stream webpageStream;
    WebResponse webpageResponse;
    StreamReader webpageReader;
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    _webRequest = WebRequest.Create(URL);
    _webRequest.Method = "POST";
    _webRequest.ContentType = "application/x-www-form-urlencoded";
    _webRequest.ContentLength = byteArray.Length;

    webpageStream = _webRequest.GetRequestStream();
    webpageStream.Write(byteArray, 0, byteArray.Length);

    webpageResponse = _webRequest.GetResponse();

    webpageStream = webpageResponse.GetResponseStream();

    webpageReader = new StreamReader(webpageStream);

    string responseFromServer = webpageReader.ReadToEnd();

    webpageReader.Close();
    webpageStream.Close();
    webpageResponse.Close();

    return responseFromServer;
}

and it works fine, but I have no idea how I can modify it to send POST data to a login script and then save a cookie(?) and log in.

I have looked at my network transfers using Firebug on the websites login page and it is sending POST data to a URL that looks like this:

accountName=myemail%40gmail.com&password=mypassword&persistLogin=on&app=com-sc2

As far as I'm aware, to be able to use my account with this website in my C# app I need to save the cookie that the web server sends, and then use it on every request? Is this right? Or can I get away with no cookie at all?

Any help is greatly apprecated, thanks! :)

Wen
  • 519
  • 4
  • 10
  • 14

2 Answers2

1

The login process depends on the concrete web site. If it uses cookies, you need to use them. I recommend to use Firefox with some http-headers watching plugin to look inside headers how they are sent to your particular web site, and then implement it the same way in C#. I answered very similar question the day before yesterday, including example with cookies. Look here.

Community
  • 1
  • 1
Al Kepp
  • 5,831
  • 2
  • 28
  • 48
  • Ah, cool. So if I'm reading this right, I just add the code to get the cookie to my login method (using the CookieContainer method) and then for every request on a page where I need to be logged in I use something like `req.CookieContainer = cookie;`? If so that seems simple enough to implement. – Wen Jan 18 '11 at 19:04
0

I've found more luck using the HtmlElement class to manipulate around websites.

Here is cross post to an example of how logging in through code would work (provided you're using a WebBrowser Control)

Community
  • 1
  • 1
DJ Olker
  • 60
  • 7