c# - HttpWebRequest 收到 "WebException: The request timed out"

标签 c# php ssl unity-game-engine httpwebrequest

经过对不同组合的无尽研究和测试,我现在一无所知。

只有当我的 byteArraySystem.Text.Encoding.UTF8.GetBytes( "")。 (比如“你好”)

服务器设置是对 Google 负载均衡器的 https 请求,它通过 HTTP 与后端通信。后端是带有 PHP 的 Apache。

出于测试目的(自签名 SSL 证书),我有这个:

System.Net.ServicePointManager.ServerCertificateValidationCallback = 
        delegate (object s,  
            System.Security.Cryptography.X509Certificates.X509Certificate certificate,  
            System.Security.Cryptography.X509Certificates.X509Chain chain, 
            System.Net.Security.SslPolicyErrors sslPolicyErrors){ 
        return true; 
    };
  • 如果我在网络浏览器 (Chrome) 中输入 URL,我会收到回复。
  • 如果我使用来自 Mozilla 的 HTTP 请求器发送或不发送内容,我都会得到正确的响应数据(在添加 SSL 安全异常(exception)之后)
  • 如果我使用 System.Text.Encoding.UTF8.GetBytes("") 运行下面的代码,一切正常(除非我无法发送数据,因此无法接收我想要的数据)

这是我正在使用的代码。

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://someurl.com/some.php");
webRequest.Proxy = null;
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.Method = "POST";
webRequest.Timeout = 3000;

byte[] byteArray = System.Text.Encoding.UTF8.GetBytes("someData");  //works if empty
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;

Stream postData = webRequest.GetRequestStream();
postData.Write(byteArray, 0, byteArray.Length);
postData.Close();

HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); //ERROR MESSAGE
Stream dataStream = webResponse.GetResponseStream();
reader = new StreamReader(dataStream);
string data = reader.ReadToEnd(); //output data

reader.Close ();
dataStream.Close ();
webResponse.Close ();

确切的错误(顺便说一句,所有这些都发生在 Unity3D 编辑器中):

WebException: 请求超时 System.Net.HttpWebRequest.EndGetResponse (IAsyncResult 异步结果) System.Net.HttpWebRequest.GetResponse()

那么,一旦 GetRequestStream 必须写入某些内容,到底为什么它不起作用?

谢谢,祝一切顺利, 克鲁格伯特


..::附录

  • 如果我增加超时时间,则需要更长的时间才能出现相同的消息。
  • 如果我写 webRequest.ContentLength = byteArray.Length+1 我会收到一个响应,但这是一个 WebException 错误:ProtocolError
  • 如果我写 webRequest.ContentLength = byteArray.Length-1 我会得到 ProtocolViolationException
  • 我已经尝试过使用 try/catch/using 导致相同的行为

最佳答案

我想通了,为什么它不起作用 - 但我仍然不知道它为什么会这样。 (也许是 UnityEditor 的事)

我加了

webRequest.ProtocolVersion = HttpVersion.Version10;

一切正常。不再有超时错误。是的,webRequest.ProtocolVersion = HttpVersion.Version11; 导致超时错误。

但是,使用以下任一方法从 Web 发出 HttpRequest 会成功:HTTP/1.1HTTP/1.0(带主机 header )HTTP/1.0 (没有主机头)

关于c# - HttpWebRequest 收到 "WebException: The request timed out",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38021166/

相关文章:

linux - 如何在 Linux 本地服务器上的 Apache 中配置 SSL?

oracle - WildFly - 将 JAR 添加到类路径

C# 使用 ftpRequest 获取完整的文件列表很慢

用于缓存权限的 PHP 全局时间戳

php - 使用自定义关闭处理程序时防止 PHP fatal error 回溯输出

javascript - AngularJS $http-Service 的问题

c# - Docker 客户端 - Windows 上的独立(可移植)版本

c# - 允许用户在 Windows 控制台中键入任意数量的字符串,然后显示有关已键入的字符串中的字母数和行号的信息

c# - 一个 UI 用于两个业务对象

java - 通过 JVM 参数相对路径加载 SSL 配置