C#中HttpClient的JSON有效负载?

时间:2011-11-20 05:33:55

标签: c# asp.net wcf json httpclient

如何传入JSON有效内容以使用REST服务。

以下是我的尝试:

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

如何将这样的内容作为参数传递给请求?:

{"SomeProp1":"abc","AnotherProp1":"123","NextProp2":"zyx"}

3 个答案:

答案 0 :(得分:16)

我从这里得到了答案: POSTing JsonObject With HttpClient From Web API

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

答案 1 :(得分:3)

这是一个类似的答案,展示了如何发布原始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!\"}"));
}

答案 2 :(得分:0)

作为严格的HTTP GET请求,我认为您不能按原样发布JSON - 您需要对其进行URL编码并将其作为查询字符串参数传递。

你可以做的是通过WebRequest / WebClient将JSON发送给POST请求的内容主体。

您可以从MSDN修改此代码示例,将您的JSON有效内容作为字符串发送,这应该可以解决问题:

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