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.
HttpWebRequest httpRequest = null;
try
{
httpRequest = WebRequest.Create(<URL>) as HttpWebRequest;
httpRequest.Method = WebRequestMethods.Http.Get;
}
catch (NotSupportedException nse)
{
// Handle Error
}
catch (ArgumentNullException ane)
{
// Handle Error
}
catch (SecurityException se)
{
// Handle Error
}
catch (UriFormatException ufe)
{
// Handle Error
}
string data = "";
HttpWebResponse httpResponse = null;
try
{
httpResponse = httpRequest.GetResponse() as HttpWebResponse;
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (Stream responseStream = httpResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
data = reader.ReadToEnd();
reader.Close();
}
responseStream.Close();
}
return true;
}
}
catch (WebException wex)
{
// Handle Error
}
catch (Exception ex)
{
// Handle Error
}
finally
{
if (response != null)
{
response.Close();
}
}
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.
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
httpRequest.ContentType = "application/x-www-form-urlencoded";
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:
Stream requestStream = null;
try
{
requestStream = httpRequest.GetRequestStream();
}
catch (Exception ex)
{
// Handle error
}
try
{
byte[] buffer = UTF8Encoding.UTF8.GetBytes(postParameter);
requestStream.Write(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
// Handle error
}
finally
{
requestStream.Close();
}
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
- Making a GET request
- Making a POST request
- Handling secure connections
References
- MSDN: HttpWebRequest Class