如何使用C#发送POST请求中的json数据
问题的原因是在使用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请求时遇到的问题。如果您在使用中有任何其他疑问,请随时提问。
问题的出现原因是需要在C#中通过POST请求发送JSON数据,但是并不清楚具体的代码实现方法。解决方法是使用HttpClient
或RestSharp
。下面是使用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(); }
这段代码的问题是在调用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;