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

通过C#中的POST发送JSON并接收返回的JSON吗?,第1张

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

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

(编辑:为了清楚起见,从问题中添加JSON)

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

使用两个代表您发布的JSON结构的类,看起来像这样:

public class Credentials{    [JsonProperty("agent")]    public Agent Agent { get; set; }    [JsonProperty("username")]    public string Username { get; set; }    [JsonProperty("password")]    public string Password { get; set; }    [JsonProperty("token")]    public string Token { get; set; }}public class Agent{    [JsonProperty("name")]    public string Name { get; set; }    [JsonProperty("version")]    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 Stringvar stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));// Wrap our JSON inside a StringContent which then can be used by the HttpClient classvar httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");using (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    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5477611.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存