Matthias Shapiro

I need fewer hobbies

Http Requests and POST for Windows Store Apps

I know this stuff, but I keep forgetting it from project to project so I figured it wouldn’t hurt anyone up here.

Scenario: You want to hit an  API and grab some data. Simple. The technique here is for Windows 8.1 and Windows Phone 8.1 and .NET 4.5 apps and can be used in a portable class library that supports those types.

First, for all you impatient types, here is the code for a simple form POST. I’m using JSON.NET so if you don’t know what that means, you’re going to want to keep reading.

var client = new HttpClient();
var requestContent = new FormUrlEncodedContent(new [] {
    new KeyValuePair<string, string>("client_id", _clientID),
    new KeyValuePair<string, string>("client_secret", _clientSecret)
});

HttpResponseMessage response = await client.PostAsync(myUrl, requestContent);
if (response.IsSuccessStatusCode)
{
    var responseContent = response.Content;
    using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
    {
        string json = await reader.ReadToEndAsync();
        var someResponse = JsonConvert.DeserializeObject<MyResponseType>(json);
    }
}

So what happened here?

HttpClient is a pretty powerful little worker bee, but can be difficult to figure out through trial and error. This is because the POST for HttpClient accepts an HttpContent object. HttpContent is an abstract class, which means that you can’t just “new HttpContent()” it. Instead, we need to use one of the derived concrete classes.

Confusing? I found this to be helpful. This is an inheritance diagram of HttpContent.

HttpContent

So if we want to actually POST something, we need to use StreamContent, ByteArrayContent, MultipartContent, StringContent, or (in this case) FormUrlEncodedContent.

The last part of this puzzle is decoding and casting the JSON object we get in response. This is easily done with two tools. The first is Json2CSharp where you can just paste in a sample JSON response and it will spit out a nice little chunk of C# code you can pull directly into your app.

The second tool is JSON.NET, which is a powerful library for serializing and deserializing JSON. Getting JSON.NET is simple. Right click on the “References” part of your app or portable class library and click on “Manage NuGet Packages…”

Manage Nuget

JSON.NET should be at the top of the list because it is stupidly popular, but you can search for it if you have to.

JSON_NET

Once you have that, you can add a reference to your class to get the JsonConvert.Deserialize method to work.

This entry was posted in Windows Phone. Bookmark the permalink.

One Response to Http Requests and POST for Windows Store Apps

  1. Pingback: Dew Drop – January 8, 2015 (#1929) | Morning Dew

Leave a Comment

Your email address will not be published.