最佳答案
这是我第一次在任何应用程序中使用 JSON 以及 System.Net
和 WebRequest
。我的应用程序应该发送一个 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();
}
}