HTTP Communication with C# – (Part II)

Making a POST Request

In our last blog post, we looked at handling HTTP GET requests from C#. In this post we take a look at the POST sibling. A POST request in C# is very similar to making a GET request. This article is the second part of the HTTP Communication with C# mini-series.

First let’s review again the code used for handling a GET request.

  1. HttpWebRequest httpRequest = null;
  2.  
  3. try
  4. {
  5.   httpRequest = WebRequest.Create(<URL>) as HttpWebRequest;
  6.   httpRequest.Method = WebRequestMethods.Http.Get;
  7. }
  8. catch (NotSupportedException nse)
  9. { 
  10.   // Handle Error
  11. }
  12. catch (ArgumentNullException ane)
  13. {
  14.   // Handle Error
  15. }
  16. catch (SecurityException se)
  17. {
  18.   // Handle Error
  19. }
  20. catch (UriFormatException ufe)
  21. {
  22.   // Handle Error
  23. }
  24.  
  25. string data = "";
  26. HttpWebResponse httpResponse = null;
  27. try
  28. {
  29.   httpResponse = httpRequest.GetResponse() as HttpWebResponse;
  30.   if (httpResponse.StatusCode == HttpStatusCode.OK)
  31.   {
  32.     using (Stream responseStream = httpResponse.GetResponseStream())
  33.     {
  34.       using (StreamReader reader = new StreamReader(responseStream))
  35.       {
  36.         data = reader.ReadToEnd();
  37.         reader.Close();
  38.       }
  39.       responseStream.Close();
  40.     }
  41.     return true;
  42.   }
  43. }
  44. catch (WebException wex)
  45. {
  46.   // Handle Error
  47. }
  48. catch (Exception ex)
  49. {
  50.   // Handle Error
  51.  }
  52. finally
  53. {
  54.   if (response != null)
  55.   {
  56.     response.Close();
  57.   }
  58. }

In lines 1 – 23 an HTTP request object is created. This object is set to use the GET method. The rest of the lines handle the response from the server. The response from the remote server does not change from a GET to POST request and throughout this article no changes will be made to these lines.

Returning back to lines 1 – 23, as one would expect the first change required is to set the Method property to POST.

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

Setting up POST Header

In a GET request all the data is part of the URL in the header. Therefore the server was required to read only the header which has a size limit. On the other hand a POST requests transmit additional data to the remote server appended to the request header. To cater for this difference two additional header fields need to be set. The first property specifies the type of data being sent. The data type helps the remote server to determine how the data is to be handled. In this article we use the data type that identifies data originating from forms.

The second property that needs to be set specifies how much data is appended to the request header. The value of this second property, ContentLength, is set to the length of the parameter string. It is important that the value assigned to this header field is exactly the size of the data. If the value specified is less than the server will partially read the data resulting in data loss. On the other hand if the value specified is more than the amount of data sent the server will block until the additional data is sent.

In our C# code the two header fields are set as follows

  1. httpRequest.ContentType = "application/x-www-form-urlencoded";
  2. httpRequest.ContentLength = postParameter.Length;

Note that the postParameter variable is a string containing the list of parameters to be sent to the server. Refer to Making a GET request for an algorithm of how to create the postParameter string.

Sending request

Now that the header has been set-up the next step is to send the request parameters. The transmission of the parameters is performed by obtaining the request stream. Then the parameters are written to the stream, which appends the parameters to the request header. This ensures that when sending the request to the server, the request will contain the all information to be transmitted.

Translating the above process to code, the C# code will look like:

  1. Stream requestStream = null;
  2.  
  3. try
  4. {
  5.   requestStream = httpRequest.GetRequestStream();
  6. }
  7. catch (Exception ex)
  8. {
  9.   // Handle error
  10. }
  11.  
  12. try
  13. {
  14.   byte[] buffer = UTF8Encoding.UTF8.GetBytes(postParameter);
  15.   requestStream.Write(buffer, 0, buffer.Length);
  16. }
  17. catch (Exception ex)
  18. {
  19.   // Handle error
  20. }
  21. finally
  22. {
  23.   requestStream.Close();
  24. }

This article builds on the first article of this mini-series. It shows how through simple modifications to the GET requests, POST requests can be handled. The next and final article of this mini-series shows how to handle connection over the HTTPS protocol.

Articles

References