kyl*_*_13 16 c# post json httpwebrequest
我正在创建一个C#控制台应用程序,它从文本文件中读取文本,将其转换为JSON格式的字符串(保存在字符串变量中),并且需要将JSON请求POST到Web api.我正在使用.NET Framework 4.
我的奋斗是使用C#创建请求并获得响应.什么是必要的基本代码?代码中的注释会很有帮助.到目前为止我得到的是下面的内容,但我不确定我是否走在正确的轨道上.
//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
Run Code Online (Sandbox Code Playgroud)
weg*_*ata 50
您是否尝试过使用WebClient类?
你应该可以使用
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)
文件在
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
归档时间: |
|
查看次数: |
96920 次 |
最近记录: |