HttpWebRequest the underlying connection was close

2019-05-05 00:48发布

问题:

I am using HttpWebRequest to POST a byte array picture through web services, the picture size is something like byte[4096]

Code:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(wsHost);
webRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
webRequest.Headers.Add(HttpRequestHeader.KeepAlive, "true");

I get an error:

The underlying connection was closed. A connection that was expected to be kept alive was closed by the server

Is it the server problem, or my posting problem?

回答1:

It could be a large number of things. Can you connect to the server otherwise?

If so, try turning off Expected 100 Continue (before you make your POST) via

System.Net.ServicePointManager.Expect100Continue = false;

According to the HTTP 1.1 protocol, when this header is sent, the form data is not sent with the initial request. Instead, this header is sent to the web server which responds with 100 (Continue) if implemented correctly. However, not all web servers handle this correctly, including the server to which I am attempting to post data.

via http://haacked.com/archive/2004/05/15/http-web-request-expect-100-continue.aspx

If that doesn't work another resource: http://geekswithblogs.net/Denis/archive/2005/08/16/50365.aspx suggests that many have solved by crafting their requests as HTTP 1.0 requests:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(wsHost);
webRequest.KeepAlive = false;
webRequest.ProtocolVersion=HttpVersion.Version10;