Implementation method of C using WebClient to log in to website and grab web page information after logging in

  • 2021-12-13 09:07:29
  • OfStack

This article describes the example of C # using WebClient to log in to the website and grab the login web page information implementation method. Share it for your reference, as follows:

C # login website is actually to simulate the browser to submit a form, and then record the session Cookie value returned by the browser response. When sending the request again, you can request with this session cookie value to realize the effect of simulated login.

The following CookieAwareWebClient implementations send requests with cookie.


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;
  }
}

The following is an example of using the mock form submission login:


var client = new CookieAwareWebClient();
client.BaseAddress = @"https://hovertree.net/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");

For more readers interested in C # related content, please check the topics on this site: "Summary of C # Coding Operation Skills", "Summary of XML File Operation Skills in C #", "Tutorial on Usage of C # Common Controls", "Summary on Usage of WinForm Controls", "Tutorial on Data Structures and Algorithms of C #," Introduction to C # Object-Oriented Programming "and" Summary on Thread Use Skills of C # Programming "

I hope this article is helpful to everyone's C # programming.


Related articles: