.NET下获取网页源码的几种方法

/// <summary>
    /// 使用WebClient方法
    /// </summary>
    protected void WebClientButton_Click(object sender, EventArgs e)
    {
        pageUrl = UrlText.Text;
        WebClient wc = new WebClient();
        wc.Credentials = CredentialCache.DefaultCredentials;

        //方法一
        byte[] pageData = wc.DownloadData(pageUrl);
        ContentHtml.Text = Encoding.Default.GetString(pageData);

        /*
        //方法二
        Stream resStream = wc.OpenRead(pageurl);
        StreamReader sr = new StreamReader(resStream, Encoding.Default);
        ContentHtml.Text = sr.ReadToEnd();
        resStream.Close();
        */

        wc.Dispose();
    }

    /// <summary>
    /// 使用WebRequest方法
    /// </summary>
    protected void WebRequestButton_Click(object sender, EventArgs e)
    {
        pageUrl = UrlText.Text;
        WebRequest wrequest = WebRequest.Create(pageUrl);
        WebResponse wresponse = wrequest.GetResponse();
        Stream resStream = wresponse.GetResponseStream();
        StreamReader sr = new StreamReader(resStream, Encoding.Default);
        ContentHtml.Text = sr.ReadToEnd();
        resStream.Close();
        sr.Close();
    }

 

public string GetRemoteHtmlCode(string Url)
    {
        string s = null;
        try
        {
            MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass();
            _xmlhttp.open("GET", Url, false, null, null);
            _xmlhttp.send("");
            if (_xmlhttp.readyState == 4)
            {
                s = System.Text.Encoding.UTF8.GetString((byte[])_xmlhttp.responseBody);
            }

           
        }
        catch
        {
        }
        return s;
    }

    public string GetRemoteHtmlCodeByGB2312(string Url)
    {
        string s = null;
        try
        {
            MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass();
            _xmlhttp.open("GET", Url, false, null, null);
            _xmlhttp.send("");
            if (_xmlhttp.readyState == 4)
            {
                s = System.Text.Encoding.Default.GetString((byte[])_xmlhttp.responseBody);
            }
        }
        catch
        {
        }
        return s;
    }

 

 

posted @ 2011-01-06 16:52  YaSin  阅读(382)  评论(0编辑  收藏  举报