如何使用C#发送POST请求中的json数据

24 浏览
0 Comments

如何使用C#发送POST请求中的json数据

我想使用C#发送POST请求时发送JSON数据。

我已经尝试了几种方法,但是遇到了很多问题。我需要使用请求主体作为原始JSON字符串和来自JSON文件的JSON数据进行请求。

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

例如:对于身份验证请求主体中的JSON --> {"Username":"myusername","Password":"pass"}

对于其他API,请求主体应该从外部JSON文件中获取。

0
0 Comments

问题的原因是在使用C#发送POST请求时,出现了一个“System.Net.WebException”的未处理异常,错误信息为“The underlying connection was closed: An unexpected error occurred on a send”。这个错误出现在调用“GetResponse()”方法时。作者在请求中添加了一个额外的头部参数 - API Key,但仍然出现相同的错误。

解决方法是在发送请求之前,设置安全协议类型。通过使用“ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;”来设置安全协议类型。作者更新了答案并解决了问题。这表明安全协议可能会导致此错误。

此外,有读者提出了如何将JSON文件内容发送到这个POST请求的问题。对此,有人指出,如果使用“using”关键字创建的StreamWriter对象,就不需要调用Flush和Close方法。

下面是解决问题的代码示例:

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

希望这篇文章能帮助您解决在C#中发送POST请求时遇到的问题。如果您在使用中有任何其他疑问,请随时提问。

0
0 Comments

问题的出现原因是需要在C#中通过POST请求发送JSON数据,但是并不清楚具体的代码实现方法。解决方法是使用HttpClientRestSharp。下面是使用HttpClient的示例代码:

using (var client = new HttpClient())
{
    // 设置请求的基地址,比如 http://www.uber.com
    client.BaseAddress = new Uri("基地址/URL地址");
    // 使用Newtonsoft JSON序列化器将JSON数据序列化,并将其添加到StringContent中
    var content = new StringContent(你的JSON, Encoding.UTF8, "application/json");
    // 设置请求的方法地址,比如 api/callUber:SomePort
    var result = await client.PostAsync("方法地址", content);
    // 将返回结果读取为字符串
    string resultContent = await result.Content.ReadAsStringAsync();
}

0
0 Comments

这段代码的问题是在调用GetResponse()方法时出现了异常,异常类型为System.Net.WebException,异常信息为The underlying connection was closed: An unexpected error occurred on a send。问题出在添加了一个额外的头部参数 - API Key。

解决方法是添加以下代码,将ServicePointManager的SecurityProtocol属性设置为SecurityProtocolType.Tls12:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

0