如何使用C#创建JSON岗位API [英] How to create JSON post to api using C#

查看:129
本文介绍了如何使用C#创建JSON岗位API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建一个C#控制台应用程序,它从一个文本文件中读取文本,把它变成一个JSON格式的字符串(在一个字符串变量中),并且需要张贴JSON请求到Web API的过程。我使用的.NET Framework 4。



我的斗争是与创建请求并得到响应,使用C#。 什么是基本的代码,有必要吗?代码中的注释将是有益的。我已经得到了迄今已是低于,但我不知道如果我在正确的轨道上。

  // POST JSON请求API 
HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(POST URL转到这里?);

request.Method =POST;
request.ContentType =应用/ JSON;

System.Text.UTF8Encoding编码=新System.Text.UTF8Encoding();
字节[]字节= encoding.GetBytes(jsonPOSTString);

request.ContentLength = bytes.Length;使用

(流requestStream = request.GetRequestStream())
{
//发送数据。
requestStream.Write(字节,0,bytes.Length);
}

//响应这里


解决方案

您是否尝试过使用WebClient类?



您应该能够使用

 字符串结果=; 
使用(VAR的客户=新的WebClient())
{
client.Headers [HttpRequestHeader.ContentType] =应用/ JSON;
结果= client.UploadString(URL,POST,JSON);
}
Console.WriteLine(结果);





文档

http://msdn.microsoft.com/en-us/library/ system.net.webclient%28V = vs.110%29.aspx



http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx


I'm in the process of creating a C# console application which reads text from a text file, turns it into a JSON formatted string (held in a string variable), and needs to POST the JSON request to a web api. I'm using .NET Framework 4.

My struggle is with creating the request and getting the response, using C#. What is the basic code that is necessary? Comments in the code would be helpful. What I've got so far is the below, but I'm not sure if I'm on the right track.

//POST JSON REQUEST TO API
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("POST URL GOES HERE?");

request.Method = "POST";
request.ContentType = "application/json";

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(jsonPOSTString);

request.ContentLength = bytes.Length;

using (Stream requestStream = request.GetRequestStream())
{
    // Send the data.
    requestStream.Write(bytes, 0, bytes.Length);
}

//RESPONSE HERE

解决方案

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);

Documentation at

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx

http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx

这篇关于如何使用C#创建JSON岗位API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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