Replace WebClient to prevent timeouts?

I am working on a C # project that uses a common XML stream for computation. I originally used XmlDocument.Load, but ported to WebClient.DownloadString so that I can include headers in my request. The channel that I access usually responds quickly, but every time now it does not respond again during the waiting period of the WebClient object, and I get an exception. Here is my code:

XmlDocument xmlDoc = new XmlDocument(); Webclient client = new WebClient(); client.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"; client.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; string data = client.DownloadString(/*URL*/); xmlDoc.LoadXml(data); 

I read that you cannot change the WebClient timeout property, and people who have this problem should use HttpWebRequest instead. Unfortunately, I do not know how to implement this, since it allows me to use my headers and send this result to xmlDoc. Due to the nature of this application, I don't care how long it takes to get the data; I can handle a user warning.

What is the best way to do this?

+4
source share
3 answers

To do this, you can use the derived WebClient class, which simply adds the timeout you want for each fetch:

 public class TimeoutWebClient : WebClient { protected override WebRequest GetWebRequest(Uri address) { HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address); request.Timeout = 60000; //1 minute timeout return request; } } 

If now you use TimeoutWebClient instead of WebClient , you will get the required timeout. If the custom headers you need are the same for each request, you can add them here, and your calling code remains very clean.

+16
source
 XmlDocument xmlDoc = new XmlDocument(); HttpWebRequest request = new (HttpWebRequest)WebRequest.Create(/*URL*/); request.Headers = new WebHeaderCollection(); // fill in request.Headers... // The response is presented as a stream. Wrap it in a StreamReader that // xmlDoc.LoadXml can accept. xmlDoc.LoadXml(new StreamReader(request.GetResponse().GetResponseStream()); 
+1
source

You can just catch the exception and then reissue the request. You might want to add some other logic to interrupt after some unsuccessful attempts.

 bool continue; do{ continue = false; try { string data = client.DownloadString(/*URL*/); } catch (WebException e) { continue = true; } } while(continue); 
0
source

All Articles