Using WebRequest to hit a RESTful web service

RESTful web services seem to be all the buzz at the moment. In my current project, I have to hit just such a service – which in fact, is simply simulating a POST request to a form.

To do this, all you need to do is create a new WebRequest (using a factory method), passing in the URL of the service that you want to hit. Once you’ve done that, it’s simply a matter of writing your request body to the request stream, and then reading a response from the response stream. You can even do it asynchronously if you want to!


/// <summary>
/// Executes a CheckMend request
/// </summary>
/// <param name="request">The CheckMend request to execute.</param>
/// <returns>A <see cref="CheckMendResponse" /> containing the results of the request</returns>
public CheckMendResponse CheckMend(CheckMendRequest request)
{
    byte[] requestBytes = request.ToASCIIByteArray();

    // Setup the web request to hit the CheckMend service
    WebRequest webRequest = WebRequest.Create(Settings.Default.CheckMendUrl);
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentLength = requestBytes.Length;

    // Write the request to the request stream
    DateTime requestTime = DateTime.Now;
    using (Stream webRequestStream = webRequest.GetRequestStream()) {
        webRequestStream.Write(requestBytes, 0, requestBytes.Length);
    }

    // Now read the response from the response stream
    using (WebResponse webResponse = webRequest.GetResponse()) {
        using (StreamReader reader = new StreamReader(webResponse.GetResponseStream())) {
            return CheckMendResponse.Parse(requestTime, reader.ReadToEnd(), request.Options);
        }
    }
}

Pretty easy, right? The only real trap is making sure that you have set the ContentType correctly:


    webRequest.ContentType = "application/x-www-form-urlencoded";

At first, I was trying with a content type of “text/html”, and that just doesn’t work.

Posted in .Net, C# by Gerrod at July 6th, 2007.

Leave a Reply