Guest User

Untitled

a guest
Mar 12th, 2019
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.28 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text;
  5. using System.Threading;
  6.  
  7. namespace ConsoleApp4
  8. {
  9.     class Program
  10.     {
  11.         static event EventHandler<string> SearchResponse;
  12.  
  13.         static void Main(string[] args)
  14.         {
  15.             SearchResponse += Program_SearchResponse;
  16.             SearchAsync("spongebob squarepants");
  17.  
  18.  
  19.             Console.Read();
  20.         }
  21.  
  22.         private static void Program_SearchResponse(object sender, string e)
  23.         {
  24.             Console.WriteLine("Got a search response of " + e.Length + " characters.");
  25.         }
  26.  
  27.         static void SearchAsync(string value)
  28.         {
  29.             HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com/?q=" + Uri.EscapeDataString(value));
  30.             request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36";
  31.             request.Proxy = default(WebProxy);
  32.             request.Headers.Set("DNT", "1");
  33.             request.Referer = "https://www.google.com/";
  34.             request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
  35.         }
  36.  
  37.         static void ResponseCallback(IAsyncResult ar)
  38.         {
  39.             if (!ar.IsCompleted)
  40.                 ar.AsyncWaitHandle.WaitOne(1000);
  41.  
  42.             HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
  43.             HttpWebResponse response;
  44.             try
  45.             {
  46.                 response = (HttpWebResponse)request.EndGetResponse(ar);
  47.             }
  48.             catch (WebException e)
  49.             {
  50.                 response = (HttpWebResponse)e.Response;
  51.             }
  52.  
  53.             if (response == null)
  54.                 return;
  55.  
  56.             if (response.StatusCode != HttpStatusCode.OK)
  57.                 return;
  58.  
  59.             ThreadPool.QueueUserWorkItem((object o) => HandleResponse(response), null);
  60.         }
  61.  
  62.         static void HandleResponse(HttpWebResponse response)
  63.         {
  64.             using (Stream stream = response.GetResponseStream())
  65.             using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, true))
  66.             {
  67.                 string html = reader.ReadToEnd();
  68.                 SearchResponse(null, html);
  69.             }
  70.         }
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment