首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C#中通过POST发送JSON并接收返回的JSON?

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

Stack Overflow用户
提问于 2014-05-11 04:23:18
回答 4查看 248.4K关注 0票数 104

这是我第一次在我的应用程序中使用JSON、System.NetWebRequest。我的应用程序应该向身份验证服务器发送一个JSON有效负载,类似于下面的负载:

代码语言:javascript
复制
{
  "agent": {                             
    "name": "Agent Name",                
    "version": 1                                                          
  },
  "username": "Username",                                   
  "password": "User Password",
  "token": "xxxxxx"
}

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

代码语言:javascript
复制
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响应,以便对其进行解析?

谢谢,Elite。

已更新代码

代码语言:javascript
复制
// 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();
    }
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23585919

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档