Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Getting data from a REST service using C#

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
Filed under: ,

[Advertisement]

Comments

DotNetKicks.com wrote Retrieving data from a REST service using C#
on 02-15-2009 3:47 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Bruno Campagnolo de Paula weblog » Resumo do dia para 2009-02-15 wrote Bruno Campagnolo de Paula weblog » Resumo do dia para 2009-02-15
on 02-15-2009 10:37 PM

Pingback from  Bruno Campagnolo de Paula weblog » Resumo do dia para 2009-02-15

Reflective Perspective - Chris Alcock » The Morning Brew #287 wrote Reflective Perspective - Chris Alcock » The Morning Brew #287
on 02-16-2009 3:37 AM

Pingback from  Reflective Perspective - Chris Alcock  » The Morning Brew #287

Bruno Campagnolo de Paula weblog » Resumo do dia para 2009-02-15 wrote Bruno Campagnolo de Paula weblog » Resumo do dia para 2009-02-15
on 02-16-2009 7:16 AM

Pingback from  Bruno Campagnolo de Paula weblog » Resumo do dia para 2009-02-15

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)