9

How to pass in a JSON payload for consuming a REST service.

Here is what I am trying:

var requestUrl = "http://example.org";

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualifiedHeaderValue("application/json"));
    var result = client.Post(requestUrl);

    var content = result.Content.ReadAsString();
    dynamic value = JsonValue.Parse(content);

    string msg = String.Format("{0} {1}", value.SomeTest, value.AnotherTest);

    return msg;
}

How do I pass something like this as a parameter to the request?:

{"SomeProp1":"abc","AnotherProp1":"123","NextProp2":"zyx"}
TruMan1
  • 33,665
  • 59
  • 184
  • 335
  • never wrap the new HttpClient() in an using block: https://learn.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/#how-to-fix-the-problem – Bernhard Sep 10 '18 at 12:53

3 Answers3

18

I got the answer from here: POSTing JsonObject With HttpClient From Web API

httpClient.Post(
    myJsonString,
    new StringContent(
        myObject.ToString(),
        Encoding.UTF8,
        "application/json"));
Community
  • 1
  • 1
TruMan1
  • 33,665
  • 59
  • 184
  • 335
3

Here's a similar answer showing how to post raw JSON:

Json Format data from console application to service stack

const string RemoteUrl = "http://www.servicestack.net/ServiceStack.Hello/servicestack/hello";

var httpReq = (HttpWebRequest)WebRequest.Create(RemoteUrl);
httpReq.Method = "POST";
httpReq.ContentType = httpReq.Accept = "application/json";

using (var stream = httpReq.GetRequestStream())
using (var sw = new StreamWriter(stream))
{
    sw.Write("{\"Name\":\"World!\"}");
}

using (var response = httpReq.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
    Assert.That(reader.ReadToEnd(), Is.EqualTo("{\"Result\":\"Hello, World!\"}"));
}
Community
  • 1
  • 1
mythz
  • 141,670
  • 29
  • 246
  • 390
0

As a strictly HTTP GET request I don't think you can post that JSON as-is - you'd need to URL-encode it and pass it as query string arguments.

What you can do though is send that JSON the content body of a POST request via the WebRequest / WebClient.

You can modify this code sample from MSDN to send your JSON payload as a string and that should do the trick:

http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

Aaronontheweb
  • 8,224
  • 6
  • 32
  • 61