As REST services are becoming more and more common the need is arising to be able to retrieve data to them via .Net. Now normally when you want to retrieve data from a web resource you commonly would do so using a web service. And when you use a web service all the ‘plumbing’ is taking care of for you by the .Net framework. However since we are not getting data from a web service there is a bit of code you need to create in order to get this data. The good news is that the amount of code you need to create is not all the bad.
In a previous post I showed how you can perform a POST to a REST Service, and you can find that post here.
Lets pretend we want to retrieve data from the following REST Service http://localhost:2844/Home/GetData. This service is going to return us a XML document, but you could have it return you a string or even a JSON result if you wanted.
Now that we know what our REST service contract looks like, we should take a look at the code needed to actually get the data.
First we are gong to take a look at the main logic needed to retrieve the data, however, there is also a helper method we need to take a look at
public string GetMessage( string endPoint )
{
HttpWebRequest request = CreateWebRequest( endPoint );
using ( var response = (HttpWebResponse) request.GetResponse( ) )
{
var responseValue = string.Empty;
if ( response.StatusCode != HttpStatusCode.OK )
{
string message = String.Format( "POST failed. Received HTTP {0}", response.StatusCode );
throw new ApplicationException( message );
}
// grab the response
using ( var responseStream = response.GetResponseStream() )
{
using ( var reader = new StreamReader( responseStream ) )
{
responseValue = reader.ReadToEnd();
}
}
return responseValue;
}
}
As you can see from the code above, the logic is pretty simply. Even though it is simple we need to take a look at a few items. First we need to get the ResponseStream and from that stream. Once we got this stream we simply need to turn this stream into a local reader and read to the end of the stream.
We also need to take a look at the helper method which will create the HttpWebRequest object. It is this object which will create the connection and setup the various content types.
private HttpWebRequest CreateWebRequest( string endPoint )
{
var request = (HttpWebRequest) WebRequest.Create( endPoint );
request.Method = "GET";
request.ContentLength = 0;
request.ContentType = "text/xml";
return request;
}
As you can see, the actual code to Retrieve a message from a REST service is simple and trivial and can be implemented with very little effort.
Till next time,
Posted
02-15-2009 2:32 AM
by
Derik Whittaker