C# 獲取網(wǎng)頁(yè)html源文件

字號(hào):


    /// <summary>
    /// 獲取網(wǎng)頁(yè)html源文件
    /// </summary>
    /// <param name="url">網(wǎng)頁(yè)地址</param>
    /// <param name="encodingStr">網(wǎng)頁(yè)文件編碼字符串</param>
    /// <returns>html源文件</returns>
    #region GetPageSource
    public static string GetPageSource(string url, string encodingStr)
    {
    HttpWebResponse res = null;
    string strResult = "";
    try
    {
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    //req.Method = "POST";
    req.KeepAlive = true;
    req.ContentType = "application/x-www-form-urlencoded";
    req.Accept = "text/Html,application/xhtml+XML,application/xml;q=0.9,*/*;q=0.8";
    req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8";
    res = (HttpWebResponse)req.GetResponse();
    StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding(encodingStr));
    strResult = reader.ReadToEnd();
    reader.Close();
    }
    catch
    {
    }
    finally
    {
    if (res != null)
    {
    res.Close();
    }
    }
    return strResult;
    }