Cerebrus

Web Scraping sample

Jul 10th, 2010
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.09 KB | None | 0 0
  1. //Related to Question at:
  2. //http://http://groups.google.com/group/dotnetdevelopment/browse_thread/thread/6a3a732e06d8598f
  3.  
  4. class NDNC
  5. {
  6.   static void Main(string[] args)
  7.   {
  8.     // Hit 1: Registered.
  9.     HitNDNC("9999774442");
  10.  
  11.     // Hit 2: Not Registered.
  12.     HitNDNC("9999988888");
  13.   }
  14.  
  15.   private static void HitNDNC(string phoneNum)
  16.   {
  17.     bool isRegistered;
  18.     string postData = string.Format("phoneno={0}", phoneNum);
  19.     // Prepare web request...
  20.     try
  21.     {
  22.       String post_response = null;
  23.  
  24.       ASCIIEncoding encoding = new ASCIIEncoding();
  25.       byte[] data = encoding.GetBytes(postData);
  26.  
  27.       HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://ndncregistry.gov.in/ndncregistry/saveSearchSub.misc");
  28.       myRequest.Method = "POST";
  29.       myRequest.ContentType = "application/x-www-form-urlencoded";
  30.       myRequest.ContentLength = data.Length;
  31.  
  32.       using (Stream rqStream = myRequest.GetRequestStream())
  33.       {
  34.         // Send the data.
  35.         rqStream.Write(data, 0, data.Length);
  36.         HttpWebResponse objResponse = (HttpWebResponse)myRequest.GetResponse();
  37.         if (objResponse != null)
  38.         {
  39.           using (StreamReader rnStream = new StreamReader(objResponse.GetResponseStream()))
  40.           {
  41.             post_response = rnStream.ReadToEnd();
  42.           }
  43.         }
  44.       }
  45.       if (!string.IsNullOrEmpty(post_response))
  46.         isRegistered = ParseResponse(post_response);
  47.       else
  48.         // An error occurred.
  49.         Console.WriteLine("An error occurred.");
  50.     }
  51.     catch (Exception ex)
  52.     {
  53.       Console.WriteLine(ex.Message);
  54.     }
  55.   }
  56.  
  57.   private static bool ParseResponse(string post_response)
  58.   {
  59.     if (post_response.Contains("This Number is Registered in NDNC Registry Database"))
  60.       return true;
  61.     else if (post_response.Contains("This Number is not Registered in NDNC Registry Database"))
  62.       return false;
  63.     else
  64.     {
  65.       //An error occurred. The required page was not found.
  66.       //Find out what the hell happened!
  67.       throw new InvalidOperationException("Oops!");
  68.     }
  69.   }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment