Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSTing JsonObject With HttpClient From Web API

I'm trying to POST a JsonObject using HttpClient from Web API. I'm not quite sure how to go about this and can't find much in the way of sample code.

Here's what I have so far:

var myObject = (dynamic)new JsonObject();
myObject.Data = "some data";
myObject.Data2 = "some more data";

HttpClient httpClient = new HttpClient("myurl");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = httpClient.Post("", ???);

I think I need to cast my JsonObject as a StreamContent but I'm getting hung up on that step.

like image 823
Mark Avatar asked May 24 '11 21:05

Mark


4 Answers

With the new version of HttpClient and without the WebApi package it would be:

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;

Or if you want it async:

var result = await client.PostAsync(url, content);
like image 142
pomber Avatar answered Sep 22 '22 16:09

pomber


The easiest way is to use a StringContent, with the JSON representation of your JSON object.

httpClient.Post(
    "",
    new StringContent(
        myObject.ToString(),
        Encoding.UTF8,
        "application/json"));
like image 27
carlosfigueira Avatar answered Sep 20 '22 16:09

carlosfigueira


Depending on your .NET version you could also use HttpClientExtensions.PostAsJsonAsync method.

https://msdn.microsoft.com/en-us/library/system.net.http.httpclientextensions.postasjsonasync.aspx

like image 74
user3285954 Avatar answered Sep 19 '22 16:09

user3285954


If using Newtonsoft.Json:

using Newtonsoft.Json;
using System.Net.Http;
using System.Text;

public static class Extensions
{
    public static StringContent AsJson(this object o)
        => new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}

Example:

var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())
like image 68
Matthew Steven Monkan Avatar answered Sep 22 '22 16:09

Matthew Steven Monkan