title: Checking internet connectivity of a system using Java
body: <p>I wrote a method which will help us finding whether the system using the proxy to connect with internet which is as follows,</p>
  
  <pre><code>try {
  
      System.out.println("Checking internet connection availability.....");
      URL u = new URL("http://www.google.com/");
      HttpURLConnection uc = (HttpURLConnection) u.openConnection();
      uc.setReadTimeout(1);//I have tried this without timeout and with it too. But it didnt work
      System.out.println(uc.getResponseCode());
  } catch (Exception ex) {
      System.out.println("Unable to connect to internet without proxy.....");
      System.out.println("Checking for any proxy settings from the PC");
      System.setProperty("java.net.useSystemProxies", "true");
      try {
          System.setProperty("java.net.useSystemProxies", "true");
          URL u = new URL("http://www.google.com/");
          HttpURLConnection uc = (HttpURLConnection) u.openConnection();
          System.out.println(uc.getResponseCode());
          System.out.println("Internet connection available");
      } catch (Exception e) {
          System.out.println("Internet connection not available :(");
      }
  }
  </code></pre>
  
  <p>Initially, I am trying to open the URL connection without proxy (assuming the system don't have proxy to connect with internet).I have set the timeout to 1 ms. Trying to get the response code from the site.
  If any error occurs means (like timeout), then in the catch block i am trying to connect to internet with system's proxy, by means of setting the <code>useSystemProxies</code> to <code>true</code>.
  But even after that also, I am not able to get the response from the site.</p>
  
  <p>I am using a system with proxy settings.</p>
  
  <p>I have tried the following too  in the catch block </p>
  
  <pre><code>Proxy next = ProxySelector.getDefault().select(new URI("http://www.google.com/")).iterator().next();
  if (next.address() != null) {
      System.out.println("Detecting Proxy configurations.....");
      String proxy = next.address().toString();
      String proxyHost = proxy.substring(0, proxy.indexOf(":"));
      String proxyPort = proxy.substring(proxy.indexOf(":") + 1);
      System.out.println("Proxy Configuration : " + proxyHost + " @ " + proxyPort);
  }
  </code></pre>
  
  <p>The above block of code also is not working. Can anyone help me out with this?</p>