Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple Usages of HttpWebRequest and RestSharp with JSON.NET

18 Oct 2013 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".

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here