经过对不同组合的无尽研究和测试,我现在一无所知。
只有当我的 byteArray
被 System.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.1
、HTTP/1.0(带主机 header )
、HTTP/1.0 (没有主机头)
关于c# - HttpWebRequest 收到 "WebException: The request timed out",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38021166/