A minimalist explanation as follows.
1. Create the HTTP Web Request
Create the WebRequest object from the from the Universal Resource Identifier (URI) you supply eg
1 2 | var webRequest = WebRequest.Create(Url); |
2. Send the HTTP request and wait for the response
1 | var responseStream = webRequest.GetResponse().GetResponseStream(); |
3. Create a StreamReader object
The StreamReader object is used to read back the text characters from the HTTP response:
I use the ‘using’ statement as a convenient means of ensure the object is subsequently disposed.
1 2 3 4 5 6 7 8 | using ( var streamReader = new StreamReader(responseStream)) { // Return next available character or -1 if there are no characters to be read while (streamReader.Peek() > -1) { Console.WriteLine(streamReader.ReadLine()); } } |
Complete code listing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | using System; using System.IO; using System.Net; namespace GetRequest { internal class Program { private static void Main( string [] args) { // Create the http request var webRequest = WebRequest.Create(Url); // Send the http request and wait for the response var responseStream = webRequest.GetResponse().GetResponseStream(); // Displays the response stream text if (responseStream != null ) { using ( var streamReader = new StreamReader(responseStream)) { // Return next available character or -1 if there are no characters to be read while (streamReader.Peek() > -1) { Console.WriteLine(streamReader.ReadLine()); } } } Console.ReadLine(); } } } |
Giving the following console output:
4. Using timeouts
To do this set the Timeout property on the WebRequest object. To demonstrate I have set this value deliberately low, not giving the web request the chance to get the HTTP reponse:
1 | webRequest.Timeout = 1; |
Example implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | using System; using System.IO; using System.Net; namespace GetRequest { internal class Program { private static void Main( string [] args) { // Create the http request var webRequest = WebRequest.Create(Url); webRequest.Timeout = 1; try { // Send the http request and wait for the response var responseStream = webRequest.GetResponse().GetResponseStream(); // Displays the response stream text if (responseStream != null ) { using ( var streamReader = new StreamReader(responseStream)) { // Return next available character or -1 if there are no characters to be read while (streamReader.Peek() > -1) { Console.WriteLine(streamReader.ReadLine()); } } } Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } |
Giving the following output: