Get html source of webpage programmatically using HttpWebRequest and HttpWebResponse

By karan patel

How to get the html source of a web page in c#

Here i have written one function called visitURL which opens the url passed in its argument and returns its html source.

         public string VisitURL(string strurl)
        {
             // request to the url
           HttpWebRequest mywebrequest = (HttpWebRequest)WebRequest.Create(strurl);
             mywebrequest.Credentials = CredentialCache.DefaultNetworkCredentials;
            mywebrequest.ContentType = " text/html";
            // get the respose
           HttpWebResponse mywebresponse = (HttpWebResponse)mywebrequest.GetResponse();
            //getting the response stream.
           StreamReader myWebSource = new StreamReader(mywebresponse.GetResponseStream());
            string myPageSource = myWebSource.ReadToEnd();
            mywebresponse.Close();
            return myPageSource;
        }


And How to Call it:

String Htmlsource  = VisitURL("http://www.google.com");

Get html source of webpage programmatically using HttpWebRequest and HttpWebResponse  (1986 Views)