POSTing JSON data using HttpClient

Recently I’ve been putting together a POC in C# that uses a RESTfull service and while there are tons of examples on how to GET data back there is very little info on how to POST data, specially if you want to POST back JSON content.

So here is a simple example, note I’ve used JSON.NET and I’m making use of the dynamic variable only available in C# 4 and above.

using (var client = new HttpClient())
{
    var request = new CreateAppRequest()
    {
        userAgent = "myAgent",
        endpointId = "1234",
        culture = "en-US"
    };

    var response = client.PostAsync("https://domain.com/CreateApp", 
        new StringContent(JsonConvert.SerializeObject(request).ToString(), 
            Encoding.UTF8, "application/json"))
            .Result;

    if (response.IsSuccessStatusCode)
    {
        dynamic content = JsonConvert.DeserializeObject(
            response.Content.ReadAsStringAsync()
            .Result);

        // Access variables from the returned JSON object
        var appHref = content.links.applications.href;
    }
}

Source: POSTing JsonObject With HttpClient From New REST API (preview release 4)

Advertisements

Published by

Alan Feekery

Developer, Gamer, Musician, Cyclist and big Motorsport fan... enjoys the odd cup of coffee :)

3 thoughts on “POSTing JSON data using HttpClient”

  1. This is the most straight forward code I have seen on PostAsync. However, I’m getting a ‘cannot perform runtime binding on a null reference’ on the last line of code (var appHref =….). Any suggestions?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s