这是我第一次在我的任何应用程序中使用 JSON 以及 System.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();
}
}
最佳答案
我发现自己在使用 HttpClient用于查询 RESTful API 的库,因为代码非常简单且完全异步。要发送此 JSON 有效负载:
{
"agent": {
"name": "Agent Name",
"version": 1
},
"username": "Username",
"password": "User Password",
"token": "xxxxxx"
}
有两个类代表您发布的 JSON 结构,可能如下所示:
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
}
https://stackoverflow.com/questions/23585919/