Request and Response in C#

This is a simple tutorial in C# on how to use the System.Net namespace to send a request and receive a response from a server. Now let's start this tutorial! 1. First we need to import System.Net. This enables us to use the required functions and classes.
  1. using System.Net;
2. This is the code for request. To send a request we first create an object of HTTPWebRequest. HttpWebRequest req = default(HttpWebRequest); We will then have an object equal to a new HTTPWebRequest with the function of '.Create()' while parsing it the server URL. req = HttpWebRequest.Create("http://www.google.com"); 3. This is the code for response. We will create an object to hold the response. This object is the type of HTTPWebResponse. To initialize, have this code: HttpWebResponse res = default(HttpWebResponse); Now, we will set the response object to the request's response.  res = req.GetResponse(); From this we can use that response to do things such as get the source of the response in a web page from the request server.
  1. using (System.IO.StreamReader reader = new System.IO.StreamReader(res.GetResponseStream()))
  2. {
  3. MessageBox.Show((string) (reader.ReadToEnd())); //Source
  4. }
  5.  
Full source code:
  1. using System.Net;
  2. using System.Windows.Forms;
  3.  
  4.  
  5. public class Form1
  6. {
  7.  
  8. private void Form1_Load(object sender, EventArgs e)
  9. {
  10. HttpWebRequest req = default(HttpWebRequest);
  11. req = HttpWebRequest.Create("http://www.google.com");
  12. HttpWebResponse res = default(HttpWebResponse);
  13. res = req.GetResponse();
  14. using (System.IO.StreamReader reader = new System.IO.StreamReader(res.GetResponseStream()))
  15. {
  16. MessageBox.Show((string) (reader.ReadToEnd())); //Source
  17. }
  18.  
  19. }
  20. }
For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below. Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment