1

I wrote the following code using httpwebrequest(Timeout=2000) and webproxy
The following code always will throw an exception because of wrong url ("ww.google.com")

When I run the program, I get two kinds of exception alternately
1. The remote server returned an error: (404) Not Found (Web Exception)
=> It takes less than 2000ms to catch this exception
=> This exception handling is normal.
.
2. A connection attempt failed because the connected party did not properly respond after a period of time or connected host has failed to respond (Socket Exception)
=> It takes 25 seconds or more to catch this exception
=> I set a request 2000ms timeout but it does not work !!!!

I want to catch exceptions if there is no response within 2 seconds
What should I do?

try 
{ 
       request = (HttpWebRequest)WebRequest.Create("https://ww.google.com"); 
       request.Proxy = proxy; 
       request.Method = "GET"; 
       request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"; 
       request.Timeout = 2000; 
       response = (HttpWebResponse)request.GetResponse(); 
       if ((response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect)) 
       { 
              StreamReader sreader = new StreamReader(response.GetResponseStream(), Encoding.Default); 
              gethtml = sreader.ReadToEnd(); 
              sreader.Close(); 
       } 
} 
catch (Exception ex) 
{ 
       throw ex; 
} 
CharithJ
  • 46,289
  • 20
  • 116
  • 131
Lady Jane
  • 25
  • 5
  • It seems like request is declared outside of your try scope. Hence its possible for other actors to alter the timeout? Maybe try declaring the response within the try scope and see how it goes. – SAm Aug 31 '17 at 00:50
  • Have you considered switching to the more modern HttpClient Api? You would be able to handle those cases in a very elegant way using CancellationTokens : https://msdn.microsoft.com/en-us/library/hh139115(v=vs.110).aspx – Cyprien Autexier Aug 31 '17 at 01:30
  • @SAm thanks for advice. As suggested, I put the httpwebrequest declaration inside a try. but,the problem still remains, but thank you – Lady Jane Aug 31 '17 at 11:06
  • @CyprienAutexier thanks I'll do what you advised me to do. – Lady Jane Sep 01 '17 at 05:32

1 Answers1

0

Ironically during testing with the invalid url https://ww.google.com you inadvertently tripped a mine. See this post for details. The MSDN documentation referred to in that post is here. Note that WebRequest.Create returns a HttpWebRequest.

Basically, it will take a while because the url isn't mapped to an IP address and thus won't be cached in the chain, requiring a full DNS lookup each time you make a request to it. There's really nothing you can do about this unless you use your own DNS caching layer in the client, but frankly it's more trouble than it's worth.

Koby Duck
  • 1,118
  • 7
  • 15