这是我第一次在任何应用程序中使用JSONSystem.Net
和WebRequest
。我的应用程序应该将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();
}
}
WebClient.UploadString(JsonConvert.SerializeObjectobj(yourobj))
或HttpClient.PostAsJsonAsync