Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

web request timeout handling?

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 20000;
using (WebResponse response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
    var result = reader.ReadToEnd();
    // Do something with result
}

In the above example I have a timeout defined, if it happens to hit the timeout how would I know, the result would be empty ?

Do I receive any reponse types ?

How can I make sure I got timed out ?

like image 839
Prix Avatar asked Mar 08 '11 11:03

Prix


People also ask

How do you handle request timeout?

Timeouts can be easily added to the URL you are requesting. It so happens that, you are using a third-party URL and waiting for a response. It is always a good practice to give a timeout on the URL, as we might want the URL to respond within a timespan with a response or an error.

How does Web API handle timeout exception?

If you really need to implement a timeout on the API side itself, I would recommend creating a thread to do your work in, and then cancelling it after a certain period. You could for example put it in a Task , create your 'timeout' task using Task. Wait and use Task. WaitAny for the first one to come back.

What is HTTP request timeout?

The HyperText Transfer Protocol (HTTP) 408 Request Timeout response status code means that the server would like to shut down this unused connection. It is sent on an idle connection by some servers, even without any previous request by the client.

What is the default timeout for HTTP request?

The default value is 100,000 milliseconds (100 seconds).


2 Answers

GetResponse() would throw a WebException. It's simple to test exactly what happens though - set the timeout to 1ms and try to hit anything which takes a while to come back.

In fact, the documentation states this explicitly:

If the timeout period expires before the resource can be returned, a WebException is thrown.

like image 160
Jon Skeet Avatar answered Nov 15 '22 09:11

Jon Skeet


Your HttpWebRequest.GetResponse call will throw a WebException when;

Abort was previously called.    
-or-    
The time-out period for the request expired.
-or-    
An error occurred while processing the request.

Catch this exception.

I used to just pull my network cable out to test this sort of thing although you could be more elegant and use a proxy tool and block that particular request.

like image 35
Dave Anderson Avatar answered Nov 15 '22 08:11

Dave Anderson