C# HttpWebRequest and HttpWebResponse

By Kenneth 'RabidDog' Clark at November 09, 2011 13:34
Filed Under: C#, Code, Web

 

Another quick post on doing a simple http request and processing the response. Working on the Google+ client for C# and due to the fact the API is REST based, I need to be able to make an HTTP request and process the HTTP response. When looking at the client I am implementing I decided to wrap the whole round trip into a single operation. Here is the results of my labor.

 

First let me give you the class definition:

 

using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;

namespace CodeShark.Communication
{
    class HttpProcessing
    {
        public static String ProcessRequest(string requestUrl)
        {
            // This will be the raw string response
            String output;

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
            httpWebRequest.MaximumAutomaticRedirections = 4;
            httpWebRequest.MaximumResponseHeadersLength = 4;

            httpWebRequest.Credentials = CredentialCache.DefaultCredentials;

            using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {

                Debug.WriteLine("Content length is {0}", httpWebResponse.ContentLength);
                Debug.WriteLine("Content type is {0}", httpWebResponse.ContentType);

                using (var responseStream = httpWebResponse.GetResponseStream())
                {
                    if(responseStream == null)
                        throw new InvalidDataException("Could not retrieve any data from the URL " + requestUrl);


                    var readStream = new StreamReader(responseStream, Encoding.UTF8);

                    output = readStream.ReadToEnd();

                    Debug.WriteLine("Response stream received.");
                    Debug.WriteLine(output);
                }
            }

            return output;
        }
    }
}
Now for a quick explanation. We create the HTTP request using the URL supplied. Then we set some limits on the bouncing the HTTP request can do and set the credentials. The request is fired off when we call the httpWebRequest.GetResponse(). Once we have the HttpWebResponse we need to read the response stream. We get the response stream by calling httpWebResponse.GetResponseStream(). Using this stream you can read the response (presumably text). Pretty simple, nothing to fancy but something we do quiet often without even knowing it.

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading








I am South African. Always have been always will be. I love my country. I love my wife and two children.


I also really enjoy solving problems. I currently work as a Software Architect exploring new solutions for business problems. Having been round the block a few times I enjoy showing new developers how best to solve problems, how to find answers and how to approach solution development.


In my spare time I enjoy riding my super bike, training in Systema and horsing around with my family.


Month List

Visitors

Twitter Feed

21. May 10:15
Still can't believe that they used american actors in Invictus. Just doesn't fit!

17. May 17:12
@UnexpectedPippa only 3? "Don't touch me on my studio!"

17. May 17:12
@SaartjieJoan if you look around you might see many forks hanging out of eye sockets

17. May 17:09
@SaartjieJoan That truly is amazing HAHAHAHA!