Friday, 5 July 2013

How to Download HTML from the URL

Step 1: Create a new console application in Visual Studio.

Step 2: Add the following lines of code to Main method

            Console.WriteLine("Enter a url");
            url = Console.ReadLine();
            PrepandHTTP();

Step 3: Copy the below code block to the class file



 public static void PrepandHTTP()
        {
            if (!url.StartsWith("http://"))
            {
                Console.WriteLine("No Http");
                url = "http://" + url;
            }
            try
            {

                WebClient webClient = new WebClient();
            webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
            WebProxy myProxy = new WebProxy("YourProxy:port", true, new string[] { }, CredentialCache.DefaultCredentials);  //if needed
            webClient.Proxy = myProxy;  //if needed
            byte[] data = webClient.DownloadData(url);
            string body = Encoding.ASCII.GetString(data);
            Console.WriteLine(body);
            Console.ReadKey();

            }
            catch (Exception ex)
            {

                throw;
            }

        }