Login to website, via C#

后端 未结 4 984
萌比男神i
萌比男神i 2020-11-22 15:56

I\'m relatively new to using C#, and have an application that reads parts of the source code on a website. That all works; but the problem is that the page in question requi

4条回答
  •  攒了一身酷
    2020-11-22 16:38

    You can simplify things quite a bit by creating a class that derives from WebClient, overriding its GetWebRequest method and setting a CookieContainer object on it. If you always set the same CookieContainer instance, then cookie management will be handled automatically for you.

    But the only way to get at the HttpWebRequest before it is sent is to inherit from WebClient and override that method.

    public 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;
        }
    }
    
    var client = new CookieAwareWebClient();
    client.BaseAddress = @"https://www.site.com/any/base/url/";
    var loginData = new NameValueCollection();
    loginData.Add("login", "YourLogin");
    loginData.Add("password", "YourPassword");
    client.UploadValues("login.php", "POST", loginData);
    
    //Now you are logged in and can request pages    
    string htmlSource = client.DownloadString("index.php");
    

提交回复
热议问题