Monday, October 27, 2008

How to get HTML code of a page?


How to get HTML code of the current page?


It's not difficult to achieve. We can get it in Page Render.

  protected   override   void   Render(HtmlTextWriter   writer)    
                System.IO.StringWriter   sw;  
                HtmlTextWriter   htmltw;  
                sw   =   new   System.IO.StringWriter();  
                htmltw   =   new   HtmlTextWriter(sw);  
                String   tempsource   =   sw.ToString();  
                //tempsource is the HTML code of the page, you can create HTML page with it to complete converting aspx to HTML.  


How to get HTML code of external page?


If you are familiar with AJAX, you must have known that XMLHttpRequest can retrieve the HTML responsed from srver asynchronously. However, XMLHttpRequest can't support cross-domain. We can't retrieve the HTML from page which is in other demain. How do we get that, how do we get HTML code from external page?


We can make use of System.Net.WebRequest to retrieve the HTML from external web page and save it to file or display on the page.

    private void saveURL(string url)
        if (!string.IsNullOrEmpty(url))
            string content = "";

            System.Net.WebRequest webRequest = WebRequest.Create(url);
            System.Net.WebResponse webResponse = webRequest.GetResponse();
            System.IO.StreamReader sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
            content = sr.ReadToEnd();
            //save to file
            StreamWriter sw = new StreamWriter(Server.MapPath("webcontent.txt"));
            //display it in this page

You can call the method like:  saveURL(""); Please pay attention on the format of URL, "http://" is necessary. Without it, you will encounter the error "The format of the URI could not be determined. "

Also, you can retrieve the HTML responsed with cross-domain through this server agent.



Anonymous said...

Autocomplete Code is not working . I use Pagemethod instead of webmethod

Vince Xu said...

Did you apply PageMethod in right way? BTW, PageMethod only can be worked in aspx page. Also, check the stipulation between server and client.