.NETアナログPOSTログインとログイン状態保持

11648 ワード

仕事でサイトにログインしてシミュレーションしてダウンロードする必要があります
まず、一つのアドレス(アドレスはユーザ名とパスワード入力ボックスがあるformのactionに対応するページ)に対してPOSTでユーザ名とパスワードを提出し(認証コードを考慮せず、もちろん認証コードも解読可能)、一つのCookieContainerでResponseのcookieを保持し、毎回同じ登録済みのセッションの使用を要求することを保証する.
このクラスのコードの一部はネット上から来て、機能は完備しなければならなくて、現在ただ登録と登録を実現した後に“バックグラウンド”のページにアクセスします.
public class LogingHelper   
  {   
      public static CookieContainer theCC = new CookieContainer();   
      /// <summary>   
      ///     (    )   
      /// </summary>   
      /// <PARAM name="url">POST     </PARAM>   
      /// <PARAM name="paramList">        name=zhangsan&pass=lisi</PARAM>   
      /// <PARAM name="referer">    </PARAM>   
      /// <RETURNS></RETURNS>   
      public static string Login(String url, String paramList, string referer)   
      {   
          HttpWebResponse res = null;   
          HttpWebRequest req = null;   
          string strResult = "";   
          try  
          {   
              req = (HttpWebRequest)WebRequest.Create(url);   
              //    header   
              req.Headers.Add(HttpRequestHeader.AcceptCharset, "GBK,utf-8;q=0.7,*;q=0.3");   
              req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");   
              req.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8");   
              req.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";   
              req.KeepAlive = true;   
              req.Referer = referer;   
              req.Headers.Add(HttpRequestHeader.CacheControl, "max-age=0");   
              req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.5 Safari/534.7";   
              req.Method = "POST";   
              req.ContentType = "application/x-www-form-urlencoded";   
              req.AllowAutoRedirect = true;   
              //  cookieContainer    cookie   
              req.CookieContainer = theCC;   
              StringBuilder UrlEncoded = new StringBuilder();   
              //     encode   
              Char[] reserved = { '?', '=', '&' };   
              byte[] SomeBytes = null;   
              if (paramList != null)   
              {   
                  int i = 0, j;   
                  while (i < paramList.Length)   
                  {   
                      j = paramList.IndexOfAny(reserved, i);   
                      if (j == -1)   
                      {   
                          UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length - i)));   
                          break;   
                      }   
                      UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j - i)));   
                      UrlEncoded.Append(paramList.Substring(j, 1));   
                      i = j + 1;   
                  }   
                  SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());   
                  req.ContentLength = SomeBytes.Length;   
                  Stream newStream = req.GetRequestStream();   
                  newStream.Write(SomeBytes, 0, SomeBytes.Length);   
                  newStream.Close();   
              }   
              else  
              {   
                  req.ContentLength = 0;   
              }   
              //       
              res = (HttpWebResponse)req.GetResponse();   
              Encoding encode = System.Text.Encoding.GetEncoding("utf-8");   
              Stream responseStream = null;   
              if (res.ContentEncoding.ToLower() == "gzip")   
              {   
                  responseStream = new System.IO.Compression.GZipStream(res.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);   
              }   
              else if (res.ContentEncoding.ToLower() == "deflate")   
              {   
                  responseStream = new System.IO.Compression.DeflateStream(res.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);   
              }   
              else  
              {   
                  responseStream = res.GetResponseStream();   
              }   
              StreamReader sr = new StreamReader(responseStream, encode);   
              strResult = sr.ReadToEnd();   
          }   
          catch (Exception e)   
          {   
              //writeLog   
          }   
          finally  
          {   
              res.Close();   
          }   
          return strResult;   
      }   
      /// <summary>      HTML   
      ///    
      /// <PARAM name="url"></PARAM>   
      /// <PARAM name="paramList"></PARAM>   
      /// <RETURNS></RETURNS>   
      public static string getPage(String url, string referer)   
      {   
          HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);   
          string strResult = string.Empty;   
          req.Headers["If-None-Match"] = "36d0ed736e88c71:d9f";   
          req.Referer = referer;   
          req.CookieContainer = theCC;   
          HttpWebResponse res = (HttpWebResponse)req.GetResponse();   
          StreamReader sr = null;   
          try  
          {   
              sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);   
              strResult = sr.ReadToEnd();   
          }   
          catch (System.Exception ex)   
          {   
              //writeLog   
          }   
          finally  
          {   
              sr.Close();   
          }   
          return strResult;   
      }   
  
      /// <summary>   
      ///       POST      
      /// </summary>   
      /// <PARAM name="url"></PARAM>   
      /// <PARAM name="referer"></PARAM>   
      /// <PARAM name="methed"></PARAM>   
      /// <PARAM name="paramList"></PARAM>   
      /// <RETURNS></RETURNS>   
      public static string VisitPage(string url, string referer, string paramList)   
      {   
          HttpWebResponse response = null;   
          string strResult = string.Empty;   
          try  
          {   
              HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;   
              request.Method = "POST";   
              request.KeepAlive = true;   
              request.Referer = referer;   
              request.Headers.Add(HttpRequestHeader.AcceptCharset, "GBK,utf-8;q=0.7,*;q=0.3");   
              request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");   
              request.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8");   
              request.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";   
              request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.5 Safari/534.7";   
              request.ContentType = "application/x-www-form-urlencoded";   
              request.CookieContainer = theCC;   
              request.Headers.Add("X-Requested-With", "XMLHttpRequest");   
              StringBuilder UrlEncoded = new StringBuilder();   
              //     encode   
              Char[] reserved = { '?', '=', '&' };   
              byte[] SomeBytes = null;   
              if (paramList != null)   
              {   
                  int i = 0, j;   
                  while (i < paramList.Length)   
                  {   
                      j = paramList.IndexOfAny(reserved, i);   
                      if (j == -1)   
                      {   
                          UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length - i)));   
                          break;   
                      }   
                      UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j - i)));   
                      UrlEncoded.Append(paramList.Substring(j, 1));   
                      i = j + 1;   
                  }   
                  SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());   
                  request.ContentLength = SomeBytes.Length;   
                  Stream newStream = request.GetRequestStream();   
                  newStream.Write(SomeBytes, 0, SomeBytes.Length);   
                  newStream.Close();   
              }   
              response = (HttpWebResponse)request.GetResponse();   
              Encoding encode = System.Text.Encoding.GetEncoding("utf-8");   
              Stream responseStream = null;   
              if (response.ContentEncoding.ToLower() == "gzip")   
              {   
                  responseStream = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);   
              }   
              else if (response.ContentEncoding.ToLower() == "deflate")   
              {   
                  responseStream = new System.IO.Compression.DeflateStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);   
              }   
              else  
              {   
                  responseStream = response.GetResponseStream();   
              }   
              StreamReader sr = new StreamReader(responseStream, encode);   
              strResult = sr.ReadToEnd();   
          }   
          catch  
          {   
              //dosomething   
          }   
          finally  
          {   
              response.Close();   
          }   
          return strResult;   
      }   
  }  
呼び出しの例
static void Main(string[] args)   
{       
string userName = "lxnanhr";       
string userPwd = "lxnanhr";       
string content = LogingHelper.Login("http://www.aa.com/index.php?c=login&m=chklogin", "uname=xxx&pass=xxx", "http://www.aa.com/index.php?c=login");       
Console.WriteLine(content);       
Console.WriteLine(LogingHelper.getPage("http://www.aa.com/index.php?c=preview&m=view&resume_id=1179406405&keyword=", "http://www.aa.com/index.php?c=search&m=supersearch#"));     Console.ReadLine();   
}