Click here to Skip to main content
Click here to Skip to main content

Simple Usages of HttpWebRequest and RestSharp with JSON.NET

, 18 Oct 2013
Rate this:
Please Sign up or sign in to vote.
Simple RestSharp and HttpWebRequest with JSON.NET examples

Introduction

Lately, I've been researching how best to consume web-hosted resources from "legacy" C# clients. By "legacy", I mean versions of .NET that predate the HttpClient object (IOW, anything prior to .NET 4.5). If you are using .NET 4.5 or better in your client, you will probably want to at least consider using the native HttpClient object.

My conclusion is that, for pre-.NET 4.5 clients, there are two primary options: HttpWebRequest and RestSharp.

Whether you choose RestSharp or HttpWebrequest depends on a few factors:

  • RestSharp is reputedly easier to use than HttpWebRequest
  • HttpWebRequest is a native C# object (it "comes in the box"); you have to install RestSharp if you want to use it; see this link and, if using an older version of Visual Studio such as VS 2008 for your client project, see this link.)
  • RestSharp is, as its name indicates, tailored towards working with REST methods
  • HttpWebRequest is most useful with non-REST resources, such as raw HTML, JSON, etc.

Using the Code

Without further ado, before I say adieux, here are the simplest possible code snippets to demonstrate how both RestSharp and HttpWebRequest are used. First, the RestSharp code, which was adapted from here.

Note: This assumes that you are consuming a REST method that returns data named "duckbilledPlatypi".

try
{
     var client = new RestClient();
     // This, of course, needs to be altered to match the
     // IP Address/Port of the server to which you are connecting
     client.BaseUrl = "http://192.128.65.42:80/";
     var request = new RestRequest();
     // The server's Rest method will probably return something
     // other than "duckbilledPlatypi" in your case
     request.Resource = "api/duckbilledPlatypi/";
     var response = client.Execute(request) as RestResponse;
     if (response != null && ((response.StatusCode == HttpStatusCode.OK) && 
      (response.ResponseStatus == ResponseStatus.Completed))) // It's probably not necessary to test both
     {
         var arr = JsonConvert.DeserializeObject<JArray>(response.Content);
         foreach (JObject obj in arr)  
         {       
             var id = (string)obj["Id"];
             var platypusId = (double)obj["PlatypusId"]
             var platypusName = (string)obj["PlatypusName"];
             MessageBox.Show(string.Format("saw id of {0}, platypusId of {1}, 
               and platypusName of {2}", id, platypusId, platypusName));
         }
     }
     else if (response != null)
     {
         MessageBox.Show(string.Format
         ("Status code is {0} ({1}); response status is {2}",
                response.StatusCode, response.StatusDescription, response.ResponseStatus));
     }  
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

Now for the HttpWebRequest code. The URI used is related to my earlier article here.

const int POINT_OF_SATISFIED_CURIOSITY = 7;
try
{
    string uri = "http://www.awardwinnersonly.com/Content/sundance.json";  // <-- this returns formatted json
    var webRequest = (HttpWebRequest)WebRequest.Create(uri);
    webRequest.Method = "GET";  // <-- GET is the default method/verb, but it's here for clarity
    var webResponse = (HttpWebResponse)webRequest.GetResponse();
    if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
    {
        var reader = new StreamReader(webResponse.GetResponseStream());
        string s = reader.ReadToEnd();
        var arr = JsonConvert.DeserializeObject<JArray>(s);
        int i = 1;
        string cat;
        string film;
        string instavid;
        string bluray;
        string dvd;
        string imghtml;
        foreach (JObject obj in arr)
        {
            cat = (string)obj["category"];
            film = (string)obj["film"];
            instavid = (string)obj["instavid"];
            bluray = (string)obj["bluray"];
            dvd = (string)obj["dvd"];
            imghtml = (string)obj["imghtml"];
            MessageBox.Show(string.Format("Object {0} in JSON array: cat == {1}, " + 
              "film == {2}, instavid == {3}, bluray == {4}, dvd == {5}, imghtml == {6}", 
                 i, cat, film, instavid, bluray, dvd, imghtml));
            i++;
            if (i > POINT_OF_SATISFIED_CURIOSITY) break;
        }
    }    
    else
    {
        //MessageBox.Show("Was fuer ein Schlamassel! Es gab irgendeine Boo-boo!
        MessageBox.Show(string.Format("Status code == {0}, Content length == {1}", 
          webResponse.StatusCode, webResponse.ContentLength)); 
    } 
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

As can be seen from the comments in the snippet directly above, HttpWebRequest can return HTML (as shown with nobelsa2f.html), or JSON (as shown with both sundance.json and GetHugos). GetHugos is actually a C# method that returns JSONized C# classes. For this reason, that (Hugo) JSON is returned unformatted; the raw json obtained from sundance.json is, OTOH, formatted. You can see this for yourself by entering any of those URLs in your browser. In the case of the HTML file (nobelsa2f.html), it will be partially rendered in your browser (but only partially, due to lack of the CSS formatting that you will see if you go here and select Books > Nobels A-F).

The code above, though, returns just the raw HTML in the webResponse.

Note that using HttpWebRequest works for downstreaming other file types, too, such as XML files, text files, CSS files, and even JavaScript/jQuery files. All the following return the files named:

You can probably grab other types of files, too, such as image files. Of course, these won't display in a MessageBox.Show(). So this is sort of a double-edged scimitar: it's cool for programmatically accessing all sorts of files on web servers (you're own, that is, unless you have permission otherwise), but it also shows that many of your files are available to anyone - which you may not like, as they might see your sloppy code or other things you'd prefer to keep private).

Then again, some of your files are available to any Thomasina, Rikki, or Henrietta anyway -- all they need to do is select the "View Page Source" context menu item from your site. However, not all of your files are accessible that way (specifically, your .js and .CSS *are* exposed, as shown above, but your .xml and .txt files are not, at least based on what I see using my site as the Guinea piglet).

Finally, you can also retrieve Rest method data using HttpWebRequest. This sort of thing...

string uri = "http://localhost:48614/api/duckbilledPlatypi"; 

...works for that.

Conclusion

So: If you just need to grab some web-hosted resources available via HTTP and are using an older version of .NET (older than 4.5), httpWebRequest is a good way to go (otherwise use HttpClient, which is not covered in this article, but can be examined here). If you are consuming REST methods, though, RestSharp is worth a try.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

B. Clay Shannon
Publisher "Found in the Translation"
United States United States
I am the entire team at "Found in the Translation," which produces multilingual books (paperback and Kindle versions) such as "Don Quixote: In Spanish and English, Paragraph-by-Paragraph" among many others (English paired with not only Spanish, but also French and even Finnish). You can see all those books here: http://jsfiddle.net/clayshannon/pRgQL/75/
 
Personal web sites that I have created can be seen at http://usamaporama.azurewebsites.net and http://bigsurgarrapata.azurewebsites.net/ and http://www.awardwinnersonly.com
 
Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.
 
I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "half cowboy, half Indian") and nonfiction: http://www.lulu.com/spotlight/blackbirdcraven
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 18 Oct 2013
Article Copyright 2013 by B. Clay Shannon
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid