WebClient website login

10,834

Anwser with solution for ppl like me :) gl

string loginData = "username=***&password=***&next=/hurt/";
            WebClient wc = new WebClient();
            string cookie = string.Empty;
            wc.BaseAddress = @"http://hurt.prosto.pl/accounts/login/";


            wc.Headers.Add("Content-Type: application/x-www-form-urlencoded");
            wc.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");
            wc.Headers.Add("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            wc.Headers.Add("Accept-Encoding: identity");
            wc.Headers.Add("Accept-Language: en-US,en;q=0.8");
            wc.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3");



            wc.UploadString("http://hurt.prosto.pl/accounts/login/", "POST", loginData);
            cookie = wc.ResponseHeaders["Set-Cookie"].ToString();
            wc.Headers.Add("Cookie", cookie);
            wc.UploadString("http://hurt.prosto.pl/accounts/login/", "POST", loginData);
            webBrowser1.DocumentText = wc.DownloadString("http://hurt.prosto.pl/hurt/myorders/--/category/all1/");
Share:
10,834
Rafal Pyndyk
Author by

Rafal Pyndyk

Updated on June 04, 2022

Comments

  • Rafal Pyndyk
    Rafal Pyndyk almost 2 years

    I have difficulties logging in to a webpage (http://hurt.prosto.pl); all the time it returns to the login page source... Any idea how to fix it?

    var loginData = new NameValueCollection();
    loginData.Add("username", username);
    loginData.Add("password", password);
    
    var client = new CookieAwareWebClient();
    client.BaseAddress = @"http://hurt.prosto.pl/accounts/login/?next=/hurt/";
    client.UploadValues("http://hurt.prosto.pl/accounts/login/?next=/hurt/", "POST", loginData);
    
    // now you are logged in and can request pages    
    string htmlSource = client.DownloadString("http://hurt.prosto.pl/hurt/myorders/--/category/all1/");
    webBrowser2.DocumentText = htmlSource;
    

    This is my CookieAwereWebClient class:

    namespace HTMLParser
    {
        internal class CookieAwareWebClient : WebClient
        {
            private CookieContainer cookie = new CookieContainer();
    
            protected override WebRequest GetWebRequest(Uri address)
            {
                WebRequest request = base.GetWebRequest(address);
                if (request is HttpWebRequest)
                {
                    (request as HttpWebRequest).CookieContainer = cookie;
                }
                return request;
            }
        }
    }
    
  • Saeb Amini
    Saeb Amini about 11 years
    You are logging in twice, no need to do that. Just set the cookie and go to your target page. Also, you do not need to set Content-Type, WebClient does that automatically.