Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.IO;
  4. using System.Text;
  5. using System.Threading;
  6.  
  7. class HttpWebRequestBeginGetRequest
  8. {
  9.     private static ManualResetEvent allDone = new ManualResetEvent(false);
  10. public static void Main(string[] args)
  11. {
  12.     // Create a new HttpWebRequest object.
  13.     HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.0.107");
  14.  
  15.     request.ContentType = "plain/text";
  16.  
  17.     request.Method = "GET";
  18.  
  19.     // start the asynchronous operation
  20.     request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
  21.  
  22.     // Keep the main thread from continuing while the asynchronous
  23.     // operation completes. A real world application
  24.     // could do something useful such as updating its user interface.
  25.     allDone.WaitOne();
  26. }
  27.  
  28. private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
  29. {
  30.     HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
  31.  
  32.     // End the operation
  33.     Stream postStream = request.EndGetRequestStream(asynchronousResult);
  34.     postStream.Close();
  35.  
  36.     // Start the asynchronous operation to get the response
  37.     request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
  38. }
  39.  
  40. private static void GetResponseCallback(IAsyncResult asynchronousResult)
  41. {
  42.     HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
  43.  
  44.     // End the operation
  45.     HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
  46.     Stream streamResponse = response.GetResponseStream();
  47.     StreamReader streamRead = new StreamReader(streamResponse);
  48.     string responseString = streamRead.ReadToEnd();
  49.     Console.WriteLine(responseString);
  50.     // Close the stream object
  51.     streamResponse.Close();
  52.     streamRead.Close();
  53.  
  54.     // Release the HttpWebResponse
  55.     response.Close();
  56.     allDone.Set();
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement