Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Threading;
- namespace ConsoleApp4
- {
- class Program
- {
- static event EventHandler<string> SearchResponse;
- static void Main(string[] args)
- {
- SearchResponse += Program_SearchResponse;
- SearchAsync("spongebob squarepants");
- Console.Read();
- }
- private static void Program_SearchResponse(object sender, string e)
- {
- Console.WriteLine("Got a search response of " + e.Length + " characters.");
- }
- static void SearchAsync(string value)
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com/?q=" + Uri.EscapeDataString(value));
- 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";
- request.Proxy = default(WebProxy);
- request.Headers.Set("DNT", "1");
- request.Referer = "https://www.google.com/";
- request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
- }
- static void ResponseCallback(IAsyncResult ar)
- {
- if (!ar.IsCompleted)
- ar.AsyncWaitHandle.WaitOne(1000);
- HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
- HttpWebResponse response;
- try
- {
- response = (HttpWebResponse)request.EndGetResponse(ar);
- }
- catch (WebException e)
- {
- response = (HttpWebResponse)e.Response;
- }
- if (response == null)
- return;
- if (response.StatusCode != HttpStatusCode.OK)
- return;
- ThreadPool.QueueUserWorkItem((object o) => HandleResponse(response), null);
- }
- static void HandleResponse(HttpWebResponse response)
- {
- using (Stream stream = response.GetResponseStream())
- using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, true))
- {
- string html = reader.ReadToEnd();
- SearchResponse(null, html);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment