以编程方式登录网站的技术

2024-04-20

我正在尝试自动登录 Photobucket 以供 API 使用,用于需要使用存储的凭据自动下载照片的项目。

API 生成一个用于登录的 URL,并且使用 Firebug 我可以查看正在发送/接收的请求和响应。

我的问题是,如何使用 HttpWebRequest 和 HttpWebResponse 来模拟 C# 中浏览器中发生的情况?

是否可以在 C# 应用程序中使用 Web 浏览器组件,填充用户名和密码字段并提交登录?


我以前做过这种事情,最终得到了一个很好的工具包来编写这些类型的应用程序。我已经使用这个工具包来处理重要的来回网络请求,所以这是完全可能的,而且并不是非常困难。

我很快发现这样做HttpWebRequest/HttpWebResponse从头开始确实比我想要处理的级别要低。我的工具完全基于Html敏捷包 http://www.codeplex.com/htmlagilitypack作者:西蒙·穆里埃。这是一个优秀的工具集。它为您完成了很多繁重的工作,并对获取的 HTML 进行解析really简单的。如果您可以使用 XPath 查询,那么 HtmlAgilityPack 就是您想要开始的地方。它也能很好地处理格式不良的 HTML!

您仍然需要一个好的工具来帮助调试。除了调试器中的内容之外,能够检查在网络上来回传输的 http/https 流量是无价的。由于您的代码将发出这些请求,而不是您的浏览器,因此 FireBug 对调试您的代码不会有太大帮助。有各种各样的数据包嗅探器工具,但对于 HTTP/HTTPS 调试,我认为您无法超越其易用性和强大功能提琴手2 http://www.fiddler2.com/fiddler2/。最新版本甚至还附带了一个 Firefox 插件,可以通过 fiddler 快速转移请求并返回。因为它还可以充当无缝 HTTPS 代理,所以您也可以检查您的 HTTPS 流量。

尝试一下,我相信它们将成为您黑客攻击中不可或缺的两个工具。

Update:添加了以下代码示例。这是从一个不太大的“Session”类中提取的,该类登录到网站并为您保留相关的 cookie。我选择它是因为它不仅仅是一个简单的“请为我获取该网页”代码,而且它还具有针对最终目标页面的一两行 XPath 查询。

public bool Connect() {
   if (string.IsNullOrEmpty(_Username)) { base.ThrowHelper(new SessionException("Username not specified.")); } 
   if (string.IsNullOrEmpty(_Password)) { base.ThrowHelper(new SessionException("Password not specified.")); }

   _Cookies = new CookieContainer();
   HtmlWeb webFetcher = new HtmlWeb();
   webFetcher.UsingCache = false;
   webFetcher.UseCookies = true;

   HtmlWeb.PreRequestHandler justSetCookies = delegate(HttpWebRequest webRequest) {
      SetRequestHeaders(webRequest, false);
      return true;
   };
   HtmlWeb.PreRequestHandler postLoginInformation = delegate(HttpWebRequest webRequest) {
      SetRequestHeaders(webRequest, false);

      // before we let webGrabber get the response from the server, we must POST the login form's data
      // This posted form data is *VERY* specific to the web site in question, and it must be exactly right,
      // and exactly what the remote server is expecting, otherwise it will not work!
      //
      // You need to use an HTTP proxy/debugger such as Fiddler in order to adequately inspect the 
      // posted form data. 
      ASCIIEncoding encoding = new ASCIIEncoding();
      string postDataString = string.Format("edit%5Bname%5D={0}&edit%5Bpass%5D={1}&edit%5Bform_id%5D=user_login&op=Log+in", _Username, _Password);
      byte[] postData = encoding.GetBytes(postDataString);
      webRequest.ContentType = "application/x-www-form-urlencoded";
      webRequest.ContentLength = postData.Length;
      webRequest.Referer = Util.MakeUrlCore("/user"); // builds a proper-for-this-website referer string

      using (Stream postStream = webRequest.GetRequestStream()) {
         postStream.Write(postData, 0, postData.Length);
         postStream.Close();
      }

      return true;
   };

   string loginUrl = Util.GetUrlCore(ProjectUrl.Login); 
   bool atEndOfRedirects = false;
   string method = "POST";
   webFetcher.PreRequest = postLoginInformation;

   // this is trimmed...this was trimmed in order to handle one of those 'interesting' 
   // login processes...
   webFetcher.PostResponse = delegate(HttpWebRequest webRequest, HttpWebResponse response) {
      if (response.StatusCode == HttpStatusCode.Found) {
         // the login process is forwarding us on...update the URL to move to...
         loginUrl = response.Headers["Location"] as String;
         method = "GET";
         webFetcher.PreRequest = justSetCookies; // we only need to post cookies now, not all the login info
      } else {
         atEndOfRedirects = true;
      }

      foreach (Cookie cookie in response.Cookies) {
         // *snip*
      }
   };

   // Real work starts here:
   HtmlDocument retrievedDocument = null;
   while (!atEndOfRedirects) {
      retrievedDocument = webFetcher.Load(loginUrl, method);
   }


   // ok, we're fully logged in.  Check the returned HTML to see if we're sitting at an error page, or
   // if we're successfully logged in.
   if (retrievedDocument != null) {
      HtmlNode errorNode = retrievedDocument.DocumentNode.SelectSingleNode("//div[contains(@class, 'error')]");
      if (errorNode != null) { return false; }
   }

   return true; 
}


public void SetRequestHeaders(HttpWebRequest webRequest) { SetRequestHeaders(webRequest, true); }
public void SetRequestHeaders(HttpWebRequest webRequest, bool allowAutoRedirect) {
   try {
      webRequest.AllowAutoRedirect = allowAutoRedirect;
      webRequest.CookieContainer = _Cookies;

      // the rest of this stuff is just to try and make our request *look* like FireFox. 
      webRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
      webRequest.Accept = @"text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
      webRequest.KeepAlive = true;
      webRequest.Headers.Add(@"Accept-Language: en-us,en;q=0.5");
      //webRequest.Headers.Add(@"Accept-Encoding: gzip,deflate");
   }
   catch (Exception ex) { base.ThrowHelper(ex); }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以编程方式登录网站的技术 的相关文章

随机推荐