Basic HttpWebRequest/Response

A friend recently asked how do you make a call to a web page via code. For example, the web page might be designed to return some data in a text-based format and filtered by query string parameters. (While this is more commonly done using a web service, it can also be accomplished by controlling the output of the HttpResponse object.) The following is a basic demonstration of how you might go about coding this in Visual C#:

/// Makes a request to a Uniform Resource Identifier (URI) for accessing data from the Internet.
/// </summary>
///The URI that identifies the Internet resource.
///The URI of the proxy server.
/// Returns a response to an Internet request.
/// Returns a message that describes the current exception.
///     GetWebResponse("", null);
private static System.String GetWebResponse(System.String requestUriString, System.String proxyAddress)
    System.Net.WebResponse webResponse = null;
    System.IO.StreamReader stream = null;
    System.String result = null;

        /* Initialize the web request. */
        System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(requestUriString);
        /* Optionally specify the User Agent. */
        webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        /* Optionally create a proxy for the request object to use if you sit behind a firewall. */
        if (System.String.IsNullOrEmpty(proxyAddress) == false)
            System.Net.WebProxy webProxy = new System.Net.WebProxy(proxyAddress);
            webRequest.Proxy = webProxy;

        /* Make a synchronous request and convert the response into something we can consume. */
        webResponse = webRequest.GetResponse();
        stream = new System.IO.StreamReader(webResponse.GetResponseStream());
        result = stream.ReadToEnd();
    catch (Exception ex)
        //TODO: Log and handle the exception rather than just pass it back.
        result = System.String.Format("Error: {0}", ex.ToString());
        /* Clean-up system resources. */
        if (stream != null) { stream.Close(); }
        if (webResponse != null) { webResponse.Close(); }

    return result;

The first step is to initialize the web request by calling the Create method in the System.Net.HttpWebRequest class. It is preferred to use this method rather than the HttpWebRequest constructor. The method takes one parameter which is the URI for the web page you want to call including any query string parameters. For example, you could use the URI for my Twitter profile: “”. In the example above, the object that is returned from the method is cast as a System.Net.HttpWebRequest rather than the default generic System.Net.WebRequest object since I can control scheme of the URI. You can also optionally specify the User Agent and/or Proxy based upon your particular requirements.

Now that the web request has been initialized, you can actually make a synchronous request to the web page by calling the GetResponse method. Up until now, you have not actually called any web page or resource. The method returns a WebResponse object that contains the actual response from the web page request. Once you have that, you can quickly stream the data returned out of the object and convert it into a string that can easily be consumed elsewhere. In the case where I have used this code before, we took the XML string that was returned from calling a third-party web page and loaded it into an XmlDocument that was then used to update a SQL Server database table.

Works on My Machine Certification ProgramAs this is my first code example, I must point out the “Works on My Machine Disclaimer”. All postings on this blog are provided “AS IS” with no warranties, confer no rights, and offer exactly zero support. If it deletes files or kills your family cat, you have been warned. It might work great, and it might not. It hasn’t been tested against the myriad of other products out there, but it works on my machine. Good luck!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.