简体   繁体   中英

JSON payload for HttpClient in C#?

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"}

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

httpClient.Post(
    myJsonString,
    new StringContent(
        myObject.ToString(),
        Encoding.UTF8,
        "application/json"));

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!\"}"));
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM