这是我第一次在我的任何应用程序中使用JSON以及System.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();

然而,与使用我过go 使用过的其他语言相比,这似乎有很多代码.我做得对吗?我怎样才能拿回JSON响应,以便我可以解析它呢?

Thanks, Elite.

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();
    }
}

推荐答案

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

{
  "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
}

Json相关问答推荐

当整个数组存储为字符串时,如何在Oracle中获取json数组的大小

从Json响应中为需要每个值的Post请求提取多个值

使用PowerShell解析文件并获取特定行的值

使用JQ将JSON输出转换为CSV复杂 struct

将不带正文的 CURL POST 转换为 RESTRequest Delphi 代码 / 为 Dropbox API /get_current_account 端点编写 Delphi 代码

使用动态语言jQuery:根据匹配模式提取与其他值匹配的值

如何使NiFi将数据库单列中的多个值转化为Solr索引中的数组?

将哈希表转换为 json 后,Powershell 缺少数组

如何将西里尔字母转换为 utf16

如何找出实际安装了哪个版本的 bower 包?

如何从 HttpClient 解析 JSON 字符串?

json.dumps 打乱了顺序

从 HttpResponse 获取 json

apple-app-site-association json 文件是否会在应用程序中更新?

在 JSON 编码的 HTML5 数据属性中转义/编码单引号

通过 RestAssured 中的 JsonPath 访问匿名数组的元素

将 javascript 对象或数组转换为 json 以获取 ajax 数据

Python 到 JSON 序列化在十进制上失败

Microsoft.Net.Http 与 Microsoft.AspNet.WebApi.Client

如何使用 Gson 将 JSONArray 转换为 List?