通过C#中的POST发送JSON并接收返回的JSON吗? [英] Send JSON via POST in C# and Receive the JSON returned?

查看:243
本文介绍了通过C#中的POST发送JSON并接收返回的JSON吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次在任何应用程序中使用JSON甚至System.NetWebRequest部分.我的应用程序应该向身份验证服务器发送类似于以下内容的JSON负载:

This is my first time to ever use JSON or even the System.Net and the WebRequest part in any of my applications. My application is supposed to send a JSON payload, similar to the one below to an authentication server:

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

要创建此有效负载,我使用了JSON.NET库.我如何将这些数据发送到身份验证服务器并接收其JSON响应?这是我在某些示例中看到的内容,但没有JSON内容:

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响应以便我可以解析它?

However, this seems to be a lot of code compaired to using other langueages i have used in the past. Am i doing this correctly? And how would i get the JSON response back so i can parse it?

谢谢,精英.

更新代码

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

推荐答案

我发现自己使用

I found myself using the HttpClient library to query RESTful APIs as the code is very straightforward and fully async'ed.

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

( Adding JSON from question for clarity)

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

具有两个表示您发布的JSON结构的类,看起来可能像这样:

With two classes representing the JSON-Structure you posted that may look like this:

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请求:

you could have a method like this, which would do your POST request:

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 = await Task.Run(() => 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");

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

这篇关于通过C#中的POST发送JSON并接收返回的JSON吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆