C#读取网站HTML内容

更详细介绍的请查看:获取HTML源码(只取文字,判断编码,过滤标签)

本章只采用GB2312编码

代码:

URL:网站地址

public String GetHtml(String Url)
        {
            string sException=null;
            string sRslt=null;
            WebResponse oWebRps=null;
            WebRequest oWebRqst=WebRequest.Create(Url);
            oWebRqst.Timeout=50000;
            try
            {
                oWebRps=oWebRqst.GetResponse();
            }
            catch(WebException e)
            {
                    sException=e.Message.ToString();
                    MessageBox.Show(sException);
            }
            catch(Exception e)
            {
                    sException=e.ToString();
                    MessageBox.Show(sException);
            }
            finally
            {
                if(oWebRps!=null)
                {
                    StreamReader oStreamRd=new StreamReader(oWebRps.GetResponseStream(),Encoding.GetEncoding("GB2312"));
                    sRslt=oStreamRd.ReadToEnd();
                    oStreamRd.Close();
                    oWebRps.Close();
                }
            }
            return sRslt;
        }