通过POST在C#中发送JSON并接收返回的JSON?


86

这是我第一次在任何应用程序中使用JSONSystem.NetWebRequest。我的应用程序应该将JSON有效负载(类似于以下内容)发送到身份验证服务器:

{
  "agent": {                             
    "name": "Agent Name",                
    "version": 1                                                          
  },
  "username": "Username",                                   
  "password": "User Password",
  "token": "xxxxxx"
}

为了创建此有效负载,我使用了JSON.NET库。如何将这些数据发送到身份验证服务器并接收其JSON响应?这是我在一些示例中看到的内容,但没有JSON内容:

var http = (HttpWebRequest)WebRequest.Create(new Uri(baseUrl));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";

string parsedContent = "Parsed JSON Content needs to go here";
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);

Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();

var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

但是,这似乎与使用我过去使用的其他语言相比有很多代码缺陷。我这样做正确吗?以及如何获取JSON响应以进行解析?

谢谢,精英。

更新的代码

// Send the POST Request to the Authentication Server
// Error Here
string json = await Task.Run(() => JsonConvert.SerializeObject(createLoginPayload(usernameTextBox.Text, password)));
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
    // Error here
    var httpResponse = await httpClient.PostAsync("URL HERE", httpContent);
    if (httpResponse.Content != null)
    {
        // Error Here
        var responseContent = await httpResponse.Content.ReadAsStringAsync();
    }
}

2
您可以尝试WebClient.UploadString(JsonConvert.SerializeObjectobj(yourobj))HttpClient.PostAsJsonAsync
LB

Answers:


128

我发现自己使用HttpClient库查询RESTful API,因为代码非常简单并且完全异步。

(编辑:为了清楚起见,从问题中添加JSON)

{
  "agent": {                             
    "name": "Agent Name",                
    "version": 1                                                          
  },
  "username": "Username",                                   
  "password": "User Password",
  "token": "xxxxxx"
}

通过两个代表您发布的JSON结构的类,看起来可能像这样:

public class Credentials
{
    [JsonProperty("agent")]
    public Agent Agent { get; set; }

    [JsonProperty("username")]
    public string Username { get; set; }

    [JsonProperty("password")]
    public string Password { get; set; }

    [JsonProperty("token")]
    public string Token { get; set; }
}

public class Agent
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("version")]
    public int Version { get; set; }
}

您可能有一个像这样的方法,它将执行您的POST请求:

var payload = new Credentials { 
    Agent = new Agent { 
        Name = "Agent Name",
        Version = 1 
    },
    Username = "Username",
    Password = "User Password",
    Token = "xxxxx"
};

// Serialize our concrete class into a JSON String
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));

// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

using (var httpClient = new HttpClient()) {

    // Do the actual request and await the response
    var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);

    // If the response contains content we want to read it!
    if (httpResponse.Content != null) {
        var responseContent = await httpResponse.Content.ReadAsStringAsync();

        // From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
    }
}

5
完美,但是等待的Task.run(()是什么?
亨特·米切尔

21
您不应该在同步的CPU绑定方法上使用Task.Run,​​因为您只是解雇一个新线程而已!
史蒂芬·福斯特

2
您不必JsonProperty为每个属性都输入。只需使用Json.Net内置的CamelCasePropertyNamesContractResolver自定义项NamingStrategy来自定义序列化过程
-Seafish

6
旁注:请勿using与一起使用HttpClient。请参阅:aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong
maxshuty

4
使用System.Net.Http.Formatting,您可以定义扩展方法:“ await httpClient.PostAsJsonAsync(” api / v1 / domain“,csObjRequest)”
hB0

13

使用JSON.NET NuGet包和匿名类型,您可以简化其他提示的建议:

// ...

string payload = JsonConvert.SerializeObject(new
{
    agent = new
    {
        name    = "Agent Name",
        version = 1,
    },

    username = "username",
    password = "password",
    token    = "xxxxx",
});

var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.PostAsync(uri, content);

// ...

6

您可以HttpContent使用的组合JObject来避免和JProperty,然后ToString()在构建时调用它StringContent

        /*{
          "agent": {                             
            "name": "Agent Name",                
            "version": 1                                                          
          },
          "username": "Username",                                   
          "password": "User Password",
          "token": "xxxxxx"
        }*/

        JObject payLoad = new JObject(
            new JProperty("agent", 
                new JObject(
                    new JProperty("name", "Agent Name"),
                    new JProperty("version", 1)
                    ),
                new JProperty("username", "Username"),
                new JProperty("password", "User Password"),
                new JProperty("token", "xxxxxx")    
                )
            );

        using (HttpClient client = new HttpClient())
        {
            var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");

            using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
            {
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return JObject.Parse(responseBody);
            }
        }

您如何避免Exception while executing function. Newtonsoft.Json: Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray错误?
加里·特尔基亚

1
HttpClient实例不应使用using结构创建。该实例应创建一次,并在整个应用程序中使用。这是因为它使用自己的连接池。您的代码通常会抛出SocketException。docs.microsoft.com/en-us/dotnet/api/...
哈伦Diluka鹤山

2

您还可以使用HttpClient()中可用的PostAsJsonAsync()方法

   var requestObj= JsonConvert.SerializeObject(obj);
   HttpResponseMessage response = await    client.PostAsJsonAsync($"endpoint",requestObj).ConfigureAwait(false);


1
您能补充说明一下您的代码做什么以及如何解决该问题吗?
Nilambar Sharma

您可以获取要发布的任何对象,并使用SerializeObject()对其进行序列化; var obj= new Credentials { Agent = new Agent { Name = "Agent Name", Version = 1 }, Username = "Username", Password = "User Password", Token = "xxxxx" }; 然后,无需将其转换为httpContent,就可以使用PostAsJsonAsync()传递端点URL和转换后的JSON对象本身。
Rukshala Weerasinghe
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.