欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#獲取網(wǎng)頁(yè)HTML源碼實(shí)例

 更新時(shí)間:2014年10月12日 16:31:04   投稿:shichen2014  
這篇文章主要介紹了C#獲取網(wǎng)頁(yè)HTML源碼的方法,是非常實(shí)用的技巧,需要的朋友可以參考下

本文實(shí)例講述了C#獲取網(wǎng)頁(yè)HTML源碼的方法,分享給大家供大家參考。具體方法如下:

關(guān)鍵代碼如下:

復(fù)制代碼 代碼如下:
/// <summary>
/// 獲取網(wǎng)頁(yè)HTML源碼
/// </summary>
/// <param name="url">鏈接 eg:http://www.baidu.com/ </param>
/// <param name="charset">編碼 eg:Encoding.UTF8</param>
/// <returns>HTML源碼</returns>
public static string GetHtmlSource(string url, Encoding charset)
{

    string _html = string.Empty;
    try
    {
 HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(url);
 HttpWebResponse _response = (HttpWebResponse)_request.GetResponse();
 using (Stream _stream = _response.GetResponseStream())
 {
     using (StreamReader _reader = new StreamReader(_stream, charset))
     {
  _html = _reader.ReadToEnd();
     }
 }
    }
    catch (WebException ex)
    {
 using (StreamReader sr = new StreamReader(ex.Response.GetResponseStream()))
 {
     _html = sr.ReadToEnd();
 }
    }
    catch (Exception ex)
    {
 _html = ex.Message;
    }
    return _html;
}

測(cè)試代碼如下:

復(fù)制代碼 代碼如下:
public static void GetHtmlSourceTest()
{
    string _url = "http://www.baidu.com/";
    string _htmlSource = HttpWebRequestUtilsV2.GetHtmlSource(_url, Encoding.UTF8);
    Console.WriteLine(_htmlSource);
}

測(cè)試效果如下圖所示:

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助

相關(guān)文章

最新評(píng)論