Wen
Wen

Reputation: 519

Logging into website programmatically with C# and WebRequest class

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! :)

Upvotes: 1

Views: 5325

Answers (2)

DJ Olker
DJ Olker

Reputation: 60

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)

Upvotes: 0

Al Kepp
Al Kepp

Reputation: 5980

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.

Upvotes: 1

Related Questions