Three methods of simulating automatic login and submission of POST information implemented by C

  • 2021-08-28 20:53:56
  • OfStack

This paper describes three methods of simulating automatic login and submission of POST information implemented by C #. Share it for your reference, as follows:

Automatic Web login (submission of Post content) has many uses, such as authentication, program upgrade, online voting, etc. The following methods are implemented with C #.

The core of web page automatic login and submission of POST information is to analyze the source code of web page (HTML). In C #, there are many components that can be used to extract HTML of web page, such as WebBrowser, WebClient and HttpWebRequest. The following three methods are used respectively:

1. WebBrowser is a "mini" browser, which is characterized by not caring about Cookie and built-in JS when Post
WebBrowser is a new component provided by VS 2005 (in fact, it encapsulates IE interface). To realize POST function, HtmlDocument is analyzed in DocumentCompleted of webBrowser. The code is as follows:


HtmlElement ClickBtn =null;
if (e.Url.ToString().ToLower().IndexOf("xxx.htm") > 0) // Landing page 
{
  HtmlDocument doc = webBrowser1.Document;
  for (int i = 0; i < doc.All.Count ; i++)
  {
   if (doc.All[i].TagName.ToUpper().Equals("INPUT"))
   {
    switch (doc.All[i].Name)
    {
     case "userCtl":
      doc.All[i].InnerText = "user01";
      break;
     case "passCt1":
      doc.All[i].InnerText = "mypass";
      break;
     case "B1":
      ClickBtn = doc.All[i]; // Submit button 
      break;
    }
   }
  }
  ClickBtn.InvokeMember("Click"); // Perform a button operation 
}

2. WebClient encapsulates some classes of HTTP, which is easy to operate. Compared with webBrowser, WebClient is characterized by its own agent, but its disadvantage is the control of COOKIE

WebClient runs all in the background, and provides the ability of asynchronous operation, so it is very convenient to concurrent multiple tasks, and then wait for the results to return, and then deal with them one by one. The code for multitasking asynchronous calls is as follows:


private void StartLoop(int ProxyNum)
{
 WebClient [] wcArray = new WebClient[ProxyNum]; // Initialization 
 for (int idArray = 0; idArray< ProxyNum;idArray++)
 {
  wcArray[idArray] = new WebClient();
  wcArray[idArray].OpenReadCompleted += new OpenReadCompletedEventHandler(Pic_OpenReadCompleted2);
  wcArray[idArray].UploadDataCompleted += new UploadDataCompletedEventHandler(Pic_UploadDataCompleted2);
  try
  {
   ......
   wcArray[idArray].Proxy = new WebProxy(proxy[1], port);
   wcArray[idArray].OpenReadAsync(new Uri("http://xxxx.com.cn/tp.asp?Id=129")); // Open WEB;
   proxy = null;
  }
  catch
  {
  }
 }
}
private void Pic_OpenReadCompleted2(object sender, OpenReadCompletedEventArgs e)
{
  if (e.Error == null)
  {
     string textData = new StreamReader(e.Result, Encoding.Default).ReadToEnd(); // Retrieve returned information 
     .....
     String cookie = ((WebClient)sender).ResponseHeaders["Set-Cookie"];
     ((WebClient)sender).Headers.Add("Content-Type", "application/x-www-form-urlencoded");
     ((WebClient)sender).Headers.Add("Accept-Language", "zh-cn");
     ((WebClient)sender).Headers.Add("Cookie", cookie);
     string postData = "......"
     byte[] byteArray = Encoding.UTF8.GetBytes(postData); //  Convert into 2 Binary array  
     ((WebClient)sender).UploadDataAsync(new Uri("http://xxxxxxy.com.cn/tp.asp?Id=129"), "POST", byteArray);
  }
}
private void Pic_UploadDataCompleted2(object sender, UploadDataCompletedEventArgs e)
{
  if (e.Error == null)
  {
   string returnMessage = Encoding.Default.GetString(e.Result);
   ......
  }
}

3. HttpWebRequest is low-level and can realize many functions, and Cookie is also very simple to operate


private bool PostWebRequest()  
{
   CookieContainer cc = new CookieContainer();
   string pos tData = "user=" + strUser + "&pass=" + strPsd;
   byte[] byteArray = Encoding.UTF8.GetBytes(postData); //  Transformation 
   HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(new Uri("http://www.xxxx.com/chk.asp"));
   webRequest2.CookieContainer = cc;
   webRequest2.Method = "POST";
   webRequest2.ContentType = "application/x-www-form-urlencoded";
   webRequest2.ContentLength = byteArray.Length;
   Stream newStream = webRequest2.GetRequestStream();
   // Send the data.
   newStream.Write(byteArray, 0, byteArray.Length); // Write parameter 
   newStream.Close();
   HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
   StreamReader sr2=new StreamReader(response2.GetResponseStream(), Encoding.Default);
   string text2 = sr2.ReadToEnd();
   ......
}

HttpWebRequest also provides asynchronous operation, interested friends check their own MSDN, it is not difficult to achieve.

Client programs emulate post submissions for many purposes, often for interface interactions between different platforms,
The landlord summed up very well, but one method was missing:


WebRequest request = WebRequest.Create(Url);
request.Method = "POST";
request.Timeout = 100000;
request.GetRequestStream().Close();
WebResponse response = request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
webInfo = sr.ReadToEnd();
sr.Close();

It's also quite convenient

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


Related articles: