HTTP Communication with C# – (Part I)

Making a GET Request

The availability and reduced costs in Internet connections opened horizons for more use. Many of today’s software leverage its use to get last minute information from remote servers. Many applications automatically check if a new version is available. Others download latest news about the product or the company which produces the product. The list of Internet use by an application can be a story or more tall. This article is the first of a mini-series that show how one can program his or her application to communicate with a remote server over HTTP using C#.

The series opens up by showing how GET requests are performed. The primary purpose of GET requests is to retrieve content identified by s specific URL. However it can also send small data to the remote server. Data sent through a GET request requires the addition of a question mark (?) to the end of the content URL and the data to follow the question mark in a key-value pattern.

Creating a GET request

The first step towards communicating with a remote server over HTTP is to define a connection to the remote server. This is done by calling the static method WebRequest.Create() and passing a URL. The URL is made up of the address of the remote server. In case of a GET request it might contain data to be sent to the remote server.

The code to initialise an HTTP request object is

  1. HttpWebRequest httpRequest = null;
  2.  
  3. try
  4. {
  5.   httpRequest = WebRequest.Create(<URL>) as HttpWebRequest;
  6. }
  7. catch (NotSupportedException nse)
  8. { 
  9.   // Handle Error
  10. }
  11. catch (ArgumentNullException ane)
  12. {
  13.   // Handle Error
  14. }
  15. catch (SecurityException se)
  16. {
  17.   // Handle Error
  18. }
  19. catch (UriFormatException ufe)
  20. {
  21.   // Handle Error
  22. }

Creating a parameter list

HTTP requests can contain data that need to be passed to the remote server. The data is passed in a bag – a list of key-value pairs. One way to build an HTTP encoded parameter list is to use a dictionary object as shown below.

  1. Dictionary<string, string> parameters = new Dictionary<string, string>();
  2. // Initialise the parameters variable with the list of items to be sent to the server.
  3.  
  4. StringBuilder parameter = new StringBuilder(string.Empty);
  5. foreach (KeyValuePair<string, string> param in parameters)
  6. {
  7.   if (parameter.Length > 0)
  8.   {
  9.     parameter.Append("&");
  10.   }
  11.   parameter.Append(param.Key + "=" + Uri.EscapeUriString(param.Value));
  12. }

In the algorithm above, we used a very important methods called Uri.EscapeUriString().The Uri.EscapeUriString() takes care of creating a new URL compliant string representing the original parameter value. This is a necessary step to ensure that values received by the remote server are interpreted correct.

Performing a GET operation

The HTTP standard requires that a connection is identified as GET, HEAD or POST request. This is done by setting the Method property.

  1. httpRequest.Method = WebRequestMethods.Http.Get;

Once the request has been set to GET, the connection can be opened for communication. A GET request contains all the information that needs to be sent to the remote server as part of the URL. The communication channel is opened by calling the GetResponse () method. When the GetResponse() is called it sends the GET request to the remote server and gets a handler to the receive channel and waits for a response from the remote server. An HTTP response code is also returned. If the response status is that everything went fine (200 OK) a handler to the data stream is obtained through the method call GetResponseStream(). The stream data is then read and processed. Finally the communication is closed to free the resources it used both from the local application and the remote server.

The above process is translatable to C# code as follows:

  1. string data = "";
  2. HttpWebResponse httpResponse = null;
  3. try
  4. {
  5.   httpResponse = httpRequest.GetResponse() as HttpWebResponse;
  6.   if (httpResponse.StatusCode == HttpStatusCode.OK)
  7.   {
  8.     using (Stream responseStream = httpResponse.GetResponseStream())
  9.     {
  10.       using (StreamReader reader = new StreamReader(responseStream))
  11.       {
  12.         data = reader.ReadToEnd();
  13.         reader.Close();
  14.       }
  15.       responseStream.Close();
  16.     }
  17.     return true;
  18.   }
  19. }
  20. catch (WebException wex)
  21. {
  22.   // Handle Error
  23. }
  24. catch (Exception ex)
  25. {
  26.   // Handle Error
  27.  }
  28. finally
  29. {
  30.   if (response != null)
  31.   {
  32.     response.Close();
  33.   }
  34. }

This article showed how to perform a GET HTTP request to a remote server. GET requests are convenient for small data however when a large amount of data needs to be sent a different type of request needs to be used. The next article of this mini-series shows how to perform a POST request that allows large amounts of data to be transmitted to the remote server.

Articles:

References