c#利用HttpWebRequest获取网页源代码,搞了好几天终于解决了,直接获取网站编码进行数据读取,再也不用担心乱码了!

命名空间:Using System.Net

         private static string GetUrlHtml(string url)
{ string strHtml = string.Empty; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse();//从Internet资源返回数据流 if (response.CharacterSet.ToLower() == "gbk")
{
using (Stream respStream = response.GetResponseStream())//读取数据流
{
using (StreamReader str = new StreamReader(respStream, Encoding.GetEncoding("gb2312")))//读取数据
{
strHtml = str.ReadToEnd();
}
}
}
else
{
using (Stream respStream = response.GetResponseStream())//读取数据流
{
using (StreamReader str = new StreamReader(respStream, Encoding.UTF8))//读取数据
{
strHtml = str.ReadToEnd();
}
}
}
return strHtml;
}
05-02 12:48