【发布时间】:2012-03-26 12:38:40
【问题描述】:
我正在调用托管在 Apache 服务器上的 API 来发布数据。我正在使用 HttpWebRequest 在 C# 中执行 POST。
API 在服务器上同时具有普通 HTTP 和安全层 (HTTPS) 端口。当我调用 HTTP URL 时,它工作得很好。但是,当我调用 HTTPS 时,它会给我超时异常(在 GetRequestStream() 函数中)。有什么见解吗?我正在使用 VS 2010、.Net 框架 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;
【问题讨论】:
-
你可以在没有 ProtocolVersion 和 ContentType 的情况下试试吗
-
还可以使用wireshark 看看网络上发生了什么。检查目标服务器是否接受跨域调用。
-
谢谢彼得。我添加了 ProtocolVersion 和 ContentType,但看起来并没有太大帮助。我将使用 wireshark 进行检查,但由于 Python 应用程序可以轻松 GET/POST 到 API,我相信服务器正在接受跨域调用。
标签: c# asp.net-mvc post https httprequest