I have a problem using HttpWebRequest class.
I create an application, which communicates with a network device (not a PC), which has a built in HTTP 1.1 server listening on port 80. For some requests, which I send to the server it answers with a short byte sequence:
HTTP/1.1 200 OK\r\n
and that's it, no more data (I check network traffic using Ethereal network monitor).
In case of such response from the server, I get a WebException on a call to HttWebRequest.GetResponse() method saying: "The underlying connection was closed: An unexpected error occured on a receive". If there are some data coming from server, then GetResponse() method returns instance of HttpWebResponse properly.
here is a code, where I get a WebException:
HttpWebRequest hwr = (HttpWebRequest) WebRequest.Create(TargetUriString);
hwr.Timeout = 10000;
hwr.Method = "POST";
hwr.UserAgent = "AddressEditor";
hwr.ContentLength = buf.Length;
hwr.KeepAlive = true;
HttpWebResponse hwResponse = null;
Stream sr = null;
// Write data
Stream s = hwr.GetRequestStream();
// Read response
hwResponse = (HttpWebResponse) hwr.GetResponse(); // WebException is thrown here !!!
if(hwResponse.StatusCode == HttpStatusCode.OK)
sr = hwResponse.GetResponseStream();
int remaining = buf.Length;
while (remaining > 0)
int read = sr.Read(buf, offset, remaining);
if (read <= 0)
remaining -= read;
offset += read;
if(sr != null)
if(hwResponse != null)
Actually, I am not completely sure, whether the problem is im my code, .NET framework or device HTTP server, because exception occurs immediately after a call to GetResponse() and the device usually answers with "HTTP/1.1 200 OK\r\n" after a approximately 5 seconds timeout, because of processing of input data. So the GetResponse() does not wait for response and just throws exception. It does not happen with this code when the server returns some data.
Could you please give me a hint:
1) Am I correctly using HttpWebrequest to write data to the remote server?
2) How to make my code block and wait untill "HTTP/1.1 200 OK\r\n" response comes from the server? (The server becomes unavailable untill it processes all input data sent by me and I can not send next requests to it untill this one ends with 200 OK)
Thank you for any help, it is really apreciated.