Click here to Skip to main content
15,890,882 members
Articles / Web Development / ASP.NET
Tip/Trick

Simple Usages of HttpWebRequest and RestSharp with JSON.NET

Rate me:
Please Sign up or sign in to vote.
4.54/5 (7 votes)
18 Oct 2013CPOL3 min read 96.1K   21   2
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".

C#
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.

C#
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...

C#
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)


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

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 "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
QuestionSaving response contents to database Pin
Member 1306269018-May-18 1:42
Member 1306269018-May-18 1:42 
GeneralMy vote of 4 Pin
Manas_Kumar14-Jan-16 19:23
professionalManas_Kumar14-Jan-16 19:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.