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;
}