If a service you want to use does not have an SDK or library for the programming language you are using, chances are you will be using their REST API to interact with the system. REST API works – excluding the technical specifications – by putting our parameters in the http query string and/or the http header and using Http POST, GET, PUT and DELETE methods to tell the API what we wish to do. For example;
This is the code used if we wish to post something in Facebook for .NET SDK:
var postparameters = new { access_token = fbAccessToken, message = TextBoxPost.Text }; dynamic result = await facebookClient.PostTaskAsync("me/feed", postparameters);
Doing the same action RESTfully would be like this:
HttpRequestMessage request = new HttpRequestMessage( System.Net.Http.HttpMethod.Post, new Uri(String.Format("https://graph.facebook.com/me/feed?access_token={0}&message={1}", fbAccessToken, WebUtility.HtmlEncode(TextBoxPost.Text)))); var response = await client.SendAsync(request);
As you can see, we set our parameters by adding them to the end of our URL. Actually, the former solution wraps the latter one for us, meaning that Facebook for .NET SDK gets the parameters from us and prepares the http requests itself to reduce our work amount.
Anyway, as I’ve said, we usually need to use REST APIs when we don’t have an SDK or library for the service we want to use. Judging from the code example above, it looks easy, right? Well, yes it is. As long as you have the documentation for it, you wouldn’t have any problems. Unless… you wanted to upload a file. Think of it, I said we put the parameters to the URL, but how do we do this with a file?
This is where multipart/form-data comes in, which is a standard way of encoding the files as byte arrays and sending them over with the http request. However, preparing our file as multipart/form-data is far from trivial, because it is very specific and requires you to delve deep into internet standards definitions to understand (if you wonder, try reading it: RFC 2388). And finally, if you wish to use it in Windows Store apps, another difficulty is that since the .NET classes are different for WinRT, the most common solutions on the internet are not usable in Windows Store apps. As of writing this, I was unable to find a working code sample.
Until now, of course. 🙂 In this article, we’ll see how we can prepare an http multipart/form-data request in Windows Store apps and upload a picture to Facebook with this method.
➤ It took me a complete (and very painful) day to put together the working code…