When running the following Java code, I get very accurate and consistent results in determining if the web page I’m testing is up.
protected synchronized boolean checkUrl(HttpURLConnection connection){ boolean error = false; //HttpURLConnection connection = null; GregorianCalendar calendar = new GregorianCalendar(); try{ if(connection != null){ connection.connect(); //200 is the expected HTTP_OK response error = processResponseCode(connection.getResponseCode()); connection.disconnect(); } else{ error = false; } }catch(java.net.UnknownHostException uhe){ ... } catch(Exception e){ ... } return error; }
The closest match to the Java pattern in c# has much higher results of false positives (mostly due to timeouts – which has a default period of 100000ms).
protected bool connectedToUrl = false; response = null; HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(this.getUri()); webreq.Credentials = CredentialCache.DefaultCredentials; WebResponse res = null;// webreq.GetResponse(); try { WebRequest request = WebRequest.Create(this.getUri()) as WebRequest; request.Credentials = CredentialCache.DefaultCredentials; if (request != null) { // Get response res = webreq.GetResponse(); connectedToUrl = processResponseCode(res); } else { logger.Fatal(getFatalMessage()); string error = string.Empty; } } catch (Exception e) { throw e; } return connectedToUrl; }
I have tried various patterns in c# to match the effectiveness of the quoted Java code, to no avail.
Any ideas?
Simply change this:
to
(Remove the declaration from earlier.)
Until you haven’t closed/disposed the response (or it’s been finalized), it’s holding onto the connection. You can only have a certain number (2 by default, I believe) of connections to any one host at a time, hence the timeouts. When you dispose the response, it allows another request to use the same connection.