,在我开始 之前
首先,如果这是一个重复的问题,请允许我事先道歉,因为似乎有几个与“现有连接被远程主机强制关闭”相关的问题,但是我似乎无法从这些其他问题中得到任何帮助,因为它们要么是与FTP (而不是HTTP)相关的问题,要么是导致请求长度问题的原因,或者我只是不明白答案。
目标
我试图使用System.Net.WebRequest对第三方服务移动应用程序推送服务 Parse.com 进行REST调用。尽管这个请求在大约95%的时间内都能工作,但是它会间歇性地抛出一个System.Net.Web异常。
我读过的一些类似的帖子表明,这可能与所发送请求的大小有关,但对我来说,这似乎不太可能,因为每次请求的大小大致相同(注:这可能是一个无知的假设)。
这里是我用来制作 请求的方法
public static WebResponse SendPushHttpRequest( string payload, string apiID, string apiKey) WebRequest request = WebRequest.Create("https://some.api.com/1/endpoint"); request.ContentType = "application/json"; request.Method = "POST"; request.Headers["Application-Id"] = apiID; request.Headers["API-Key"] = apiKey; byte[] buffer = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(payload); //string result = Convert.ToBase64String(buffer); Stream reqstr = request.GetRequestStream(); reqstr.Write(buffer, 0, buffer.Length); reqstr.Close(); using (WebResponse response = request.GetResponse()) return response; catch (Exception ex) throw ex; }
这里是抛出的System.Net.Web异常,基础连接已关闭:在接收时发生意外错误。
无法从传输连接读取数据的内部异常:现有连接被远程主机强制关闭。“} System.SystemException {System.IO.IOException}
异常状态ReceiveFailure
堆栈跟踪
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
来自Web 的响应
GenericParameterAttributes '(((System.Reflection.RuntimeMethodInfo)(((System.Exception)(ex)).TargetSite)).ReturnType).GenericParameterAttributes'
抛出'System.InvalidOperationException‘System.Reflection.GenericParameterAttributes {System.InvalidOperationException}类型的异常。
消息:“方法只能在Type.IsGenericParameter为真的类型上调用。”字符串
和最后但并非最不重要的原始HTTP请求
POST http://localhost:58746/mobile/SendPushV2 HTTP/1.1 Host: localhost:58746 Connection: keep-alive Content-Length: 140 Accept: */* Origin: http://localhost:58746 X-Requested-With: XMLHttpRequest User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Referer: http://localhost:58746/Mobile Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3