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.
d0a46d0a-2c5e-49d1-9fa7-5ec9deff288d|0|.0