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

这是我第一次在任何应用程序中使用 JSON 以及 System.NetWebRequest。我的应用程序应该发送一个 JSON 有效负载,类似于下面的一个到身份验证服务器:

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

To create this payload, I used the JSON.NET library. How would I send this data to the authentication server and receive its JSON response back? Here is what I have seen in some examples, but no JSON content:

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 响应以便解析它呢?

谢谢,精英。

Updated Code

// 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();
}
}
295543 次浏览

我发现自己使用 HttpClient库来查询 RESTful API,因为代码非常简单,而且是完全异步的。要发送这个 JSON 有效负载:

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

With two classes representing the JSON structure you posted that may look like this:

public class Credentials
{
public Agent Agent { get; set; }
    

public string Username { get; set; }
    

public string Password { get; set; }
    

public string Token { get; set; }
}


public class Agent
{
public string Name { get; set; }
    

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 = 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");


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
}

你可以使用 JObjectJProperty的组合来构建你的 HttpContent,然后在构建 StringContent时调用 ToString():

        /*{
"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);
}
}

使用 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);


// ...

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

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