我正在调用托管在 Apache 服务器上的 API 来发布数据。我正在使用 HttpWebRequest 在 C# 中执行 POST。
API 在服务器上同时具有普通 HTTP 和安全层 (HTTPS) 端口。当我调用 HTTP URL 时,它工作得很好。但是,当我调用 HTTPS 时,它会给我超时异常(在 GetRequestStream() 函数中)。有什么见解吗?我正在使用 VS 2010、.Net Framework 3.5 和 C#。这是代码块:
string json_value = jsonSerializer.Serialize(data);
HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create("https://server-url-xxxx.com");
request.Method = "POST";
request.ProtocolVersion = System.Net.HttpVersion.Version10;
request.ContentType = "application/x-www-form-urlencoded";
byte[] buffer = Encoding.ASCII.GetBytes(json_value);
request.ContentLength = buffer.Length;
System.IO.Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
编辑: Peter 建议的控制台程序运行良好。但是当我添加需要发布到 API 的数据(JSON 格式)时,它会抛出操作超时异常。这是我添加到基于控制台的应用程序的代码,它会抛出错误。
byte[] buffer = Encoding.ASCII.GetBytes(json_value);
request.ContentLength = buffer.Length;
最佳答案
我遇到了同样的问题。对我来说似乎已经解决了。我检查了所有代码,确保为所有 HttpWebResponse 对象调用 webResponse.Close() 和/或 responseStream.Close()。文档指示您可以关闭流或 HttpWebResponse 对象。调用两者都没有害处,所以我这样做了。不关闭响应可能会导致应用程序耗尽连接以供重用,据我在代码中观察到,这似乎会影响 HttpWebRequest.GetRequestStream。
关于c# - 将数据发布到 HTTPS URL 时,GetRequestStream() 抛出超时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9627669/