【问题标题】:JSON payload for HttpClient in C#?C# 中 HttpClient 的 JSON 有效负载?
【发布时间】:2012-01-02 05:39:10
【问题描述】:

如何传入 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"}

【问题讨论】:

标签: c# asp.net wcf json httpclient


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多