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
HttpWebRequest httpRequest = null;
try
{
httpRequest = WebRequest.Create(<URL>) as HttpWebRequest;
}
catch (NotSupportedException nse)
{
// Handle Error
}
catch (ArgumentNullException ane)
{
// Handle Error
}
catch (SecurityException se)
{
// Handle Error
}
catch (UriFormatException ufe)
{
// Handle Error
}
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.
Dictionary<string, string> parameters = new Dictionary<string, string>();
// Initialise the parameters variable with the list of items to be sent to the server.
StringBuilder parameter = new StringBuilder(string.Empty);
foreach (KeyValuePair<string, string> param in parameters)
{
if (parameter.Length > 0)
{
parameter.Append("&");
}
parameter.Append(param.Key + "=" + Uri.EscapeUriString(param.Value));
}
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.
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:
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();
}
}
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:
- Making a GET Request
- Making a POST Request
- Handling secure connections