Suppose I create a HTTPWebRequest
, call its GetResponse()
and start reading from the response stream. If the connection is interrupted while reading from the stream, do I have to wait for it to time out, or can I know right away that something's gone wrong? No exception is thrown when I interrupt the connection (eg I disconnect my computer from the network).
It depends on the situation.
In general you'll need to be prepared for both situations (immediate and late interruption). If, for example, the server disconnects you, you'll know relatively quickly.
See http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus for the kinds of errors that can occur (the WebRequest
classes throw WebException
s on errors)
You have a variety of options:
BeginGet...
and EndGet...
) and model your application around this. Basically you'll be notified "at some point" if there was a success or error. Do something else in the meantime ReadTimeout
on the acquired stream (See comment on the other answer, set Timeout
on the request as well). Re-try or whatever. You dont have to worry if the request is interrupted or not.
You can specify explicit timeout as follows. If its interrupted you will get exception.
try
{
var request = HttpWebRequest.Create(url);
request.Timeout = 3000;
var response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode.Equals(HttpStatusCode.OK))
{
//do stuff
}
}
catch (Exception exception)
{
exception.ToLog();
}
最有可能您必须等待超时
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.