I have a really simple question. I am uploading files to a server using HTTP POST. The thing is I need to specially handle connection timeouts and add a bit of a waiting algorithm after a timeout has occurred to relive the server.
My code is pretty simple:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("SomeURI"); request.Method = "POST"; request.ContentType = "application/octet-stream"; request.KeepAlive = true; request.Accept = "*/*"; request.Timeout = 300000; request.AllowWriteStreamBuffering = false; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { WebHeaderCollection headers = response.Headers; using (Stream Answer = response.GetResponseStream()) { // Handle. } } } catch (WebException e) { if (Timeout_exception) { //Handle timeout exception } }
I omitted the file reading code as it is not our concern. Now I need to make sure that once a WebException is thrown, I filter the exception to see if it is indeed a timeout exception. I thought of comparing against the exception message yet I am not sure if this is the right way since the application in question is a commercial app and I am afraid that the message varies between different languages. And what message should I be looking for.
Any suggestions?
The default value is 100,000 milliseconds (100 seconds).
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.
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.
You can look at WebException.Status
. The WebExceptionStatus
enum has a Timeout
flag:
try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { WebHeaderCollection headers = response.Headers; using (Stream answer = response.GetResponseStream()) { // Do stuff } } } catch (WebException e) { if (e.Status == WebExceptionStatus.Timeout) { // Handle timeout exception } else throw; }
Using C# 6 exception filters can come in handy here:
try { var request = WebRequest.Create("http://www.google.com"); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { WebHeaderCollection headers = response.Headers; using (Stream answer = response.GetResponseStream()) { // Do stuff } } } catch (WebException e) when (e.Status == WebExceptionStatus.Timeout) { // If we got here, it was a timeout exception. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With