【问题标题】:How to send json data in POST request using C# [duplicate]如何使用 C# 在 POST 请求中发送 json 数据 [重复]
【发布时间】:2017-11-24 09:18:44
【问题描述】:

我想使用 C# 在 POST 请求中发送 json 数据。

我尝试了几种方法,但面临很多问题。我需要使用请求正文作为来自字符串的原始 json 和来自 json 文件的 json 数据来请求。

如何使用这两种数据形式发送请求。

Ex: json 中的认证请求体 --> {"Username":"myusername","Password":"pass"}

对于其他 API,请求正文应从外部 json 文件中检索。

【问题讨论】:

  • 你能把你的代码放在这里,我们很容易理解

标签: c# json asp.net-mvc web-services rest


【解决方案1】:

你可以用HttpWebRequest做到这一点:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

【讨论】:

  • 这显示错误:An unhandled exception of type 'System.Net.WebException' occurred in System.dll Additional information: The underlying connection was closed: An unexpected error occurred on a send 涉及 GetResponse()。我只添加了一个额外的标头参数 - API Key
  • 你可以试试 httpWebRequest.KeepAlive = false; 吗?我已经更新了答案。
  • 不,同一行中仍然有同样的错误!
  • 安全协议会导致这个错误,你也可以试试ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 |安全协议类型.Tls11 |安全协议类型.Tls;。更新了答案。
  • 据我了解,如果 Streamwriter 是使用 using 创建的,则不需要 Flush and Close。
【解决方案2】:

您可以使用HttpClientRestSharp。由于我不知道你的代码是什么,这里是一个使用HttpClient的例子:

using (var client = new HttpClient())
{
    // This would be the like http://www.uber.com
    client.BaseAddress = new Uri("Base Address/URL Address");

    // serialize your json using newtonsoft json serializer then add it to the StringContent
    var content = new StringContent(YourJson, Encoding.UTF8, "application/json") 

    // method address would be like api/callUber:SomePort for example
    var result = await client.PostAsync("Method Address", content);
    string resultContent = await result.Content.ReadAsStringAsync();   
}

【讨论】:

  • ^^不讨厌,但现在它是我帖子的副本^^
  • @NtFreX 这就是我投票支持它的原因:)
【解决方案3】:

这对我有用。

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

【讨论】:

  • 这也显示与上述答案相同的错误:System.dll 中发生了“System.Net.WebException”类型的未处理异常附加信息:底层连接已关闭:发生意外错误当涉及到 GetResponse() 时发送。我只添加了一个额外的标头参数 - API Key
猜你喜欢
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
  • 1970-01-01
  • 2018-08-09
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 2021-01-10
相关资源
最近更新 更多