根据url,得到其html源文件 + post用户认证

/// <summary>
  /// 根据url,得到其html源文件
  /// </summary>
  /// <param name="url"></param>
  /// <returns></returns>
  public static string GetHtmlStr(string url)
  {
   StreamReader sr = null;
   string html = "";
   try
   {
    WebRequest wrq = WebRequest.Create(url);
    WebResponse wrs = wrq.GetResponse();
    Stream strm = wrs.GetResponseStream();
    System.Text.Encoding resEncoding = System.Text.Encoding.Default;//接收的编码
    sr = new StreamReader(strm,resEncoding);

    Char[] read = new Char[256];
    int count = sr.Read( read, 0, 256 );
    while (count > 0)
    {
     String str = new String(read, 0, count);
     html += str;
     count = sr.Read(read, 0, 256);
    }
   }
   catch{}
   return html;
  }
 
/// <summary>
  /// post用户认证
  /// </summary>
  /// <param name="url"></param>
  /// <param name="param"></param>
  /// <returns></returns>
  public static string PostUserCheck(string url,string param)
  {
   string cookieheader;
   HttpWebResponse res = null;

   HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
   req.Method = "POST";
   req.ContentType = "application/x-www-form-urlencoded";
   req.AllowAutoRedirect = false;
   CookieContainer cookieCon = new CookieContainer();
   req.CookieContainer = cookieCon;

   System.Text.StringBuilder postData = new System.Text.StringBuilder( 1000 );
   postData.Append(param);

   req.ContentLength = postData.ToString().Length;
   Stream _RequestStream = req.GetRequestStream();
   _RequestStream.Write( Encoding.Default.GetBytes( postData.ToString() ), 0, postData.ToString().Length );
   _RequestStream.Close();

   try
   {
    res = (HttpWebResponse)req.GetResponse();
   }
   catch{}

   cookieheader = req.CookieContainer.GetCookieHeader(new Uri(url));
   return cookieheader;
  }

posted @ 2006-03-30 10:44  DotNet菜园  阅读(691)  评论(0)    收藏  举报