c# - 将数据发布到 HTTPS URL 时,GetRequestStream() 抛出超时异常

标签 c# asp.net-mvc post https httprequest

我正在调用托管在 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/

相关文章:

c# - .NET SVCUTIL 未正确生成命名空间

c# - 在提供 ISigningCredentialStore 的自定义实现后,Identity Server 仍将内存中的 key 包含在发现文档中

.net - 如何保持验证 DRY?

javascript - 从 document.ready 调用 jQuery 插件抛出 getPreventDefault 错误

asp.net-mvc - 如果我的应用程序使用 Azure "Easy Auth",如何向 Microsoft Graph 进行身份验证

c# - 使用 XAML C# 删除背景动画?

c# - 在 .NET 中将 Markdown 转换为 HTML

json - 在经典 ASP 中使用 json2.js

javascript - Opera 中 POST 的 jQuery 语法错误

php - 自定义 Shopware6 路由给出 "405 Method Not Allowed"