C#模拟登陆

来源:互联网 发布:显为人知的外国作家 编辑:程序博客网 时间:2024/05/21 09:04

    模拟登陆,目的是方便抓取需要登陆后浏览的论坛帖子。

    代码摘录如下(注意黑体部分):

//Request #1 (the login)    
   HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
   objRequest.Method = "POST";
   objRequest.ContentLength = strPost.Length;
   objRequest.ContentType = "application/x-www-form-urlencoded";         
   objRequest.CookieContainer = new CookieContainer();

   try
   {
      myWriter = new StreamWriter(objRequest.GetRequestStream());
      myWriter.Write(strPost);
   }
   catch (Exception e)
   {
      Console.WriteLine(e.Message);
   }
   finally
   {
      myWriter.Close();
   }
      
   HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
   //retain the cookies   
   foreach (Cookie cook in objResponse.Cookies)
   {
      myContainer.Add(cook);
   }

   
   //Check out the html.   
   using (StreamReader sr =
          new StreamReader(objResponse.GetResponseStream()) )
   {
      String test = sr.ReadToEnd();

      // Close and clean up the StreamReader      
      sr.Close();
   }

原创粉丝点击