POSTing JSON data using HttpClient

[Originally Posted By]: https://alanfeekery.com/2015/04/13/posting-json-data-using-httpclient/

Recently I’ve been putting together a POC in C# that uses a RESTfullservice 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

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