title: How to quickly check if URL server is available
body: <p>I have a URL in the form</p>
  
  <pre><code>http://www.mywebsite.com/util/conv?a=1&amp;from=%s&amp;to=%s
  </code></pre>
  
  <p>And want to check if it is available.</p>
  
  <p>The links redirect me on a bad request page if I try to open these with a browser, however via code I can get the data that I need.</p>
  
  <p>Using a try-catch block on a HTTP request procedure is pretty slow, so I'm wondering how I could ping a similar address to check if its server is active.</p>
  
  <hr>
  
  <p>I have tried</p>
  
  <pre><code>boolean reachable = InetAddress.getByName(myLink).isReachable(6000);
  </code></pre>
  
  <p>But returns always <code>false</code>.</p>
  
  <p>I have also tried</p>
  
  <pre><code>public static boolean exists(String URLName) {
  
      try {
          HttpURLConnection.setFollowRedirects(false);
          HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
          con.setConnectTimeout(1000);
          con.setReadTimeout(1000);
          con.setRequestMethod("HEAD");
          return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
      } catch (Exception e) {
          e.printStackTrace();
          return false;
      }
  }
  </code></pre>
  
  <p>That returns the correct value at the end of the process, bit is too slow if server is not available.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I have understood what is the cause of slowness</p>
  
  <p>a) if server returns some data but interrupts the request before complete the request the timeout is ignored and stuck until returns an <code>Exception</code> that lead the execution to reach the catch block, this is the cause of the slowness of this method, and still I haven't found a valid solution to avoid this.</p>
  
  <p>b) If I start the android device and open the App without connection, the false value is returned correctly, if the app is opened with internet connection active and the device lost its internet connection happens the same thing of the case A (also if I try to terminate and restart the App... I don't know why, I suppose that something remains cached)</p>
  
  <p>All this seems related to the fact <code>Java URLConnection</code>  doesn't provide no fail-safe timeout on reads. Looking at the sample at <a href="http://thushw.blogspot.it/2010/10/java-urlconnection-provides-no-fail.html">this link</a> I have seen that uses a thread to interrupt the connection in some way but if I add simply the line <code>new Thread(new InterruptThread(Thread.currentThread(), con)).start();</code> like in the sample nothing changes.</p>