sábado, 2 de maio de 2015

Classe para verificar conexão com a Internet

public class Internet {

    public static boolean verificarConexao() {
        try {
            java.net.URL google = new java.net.URL("http://www.google.com");
            java.net.URLConnection conn = google.openConnection();
           

            java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) conn;
            httpConn.connect();
            int x = httpConn.getResponseCode();
            if (x == 200) {
                return true;
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(Internet.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (IOException ex) {
            Logger.getLogger(Internet.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
       
        return false;
    }

    public static boolean verificarConexao(String url) {
        try {
            java.net.URL teste = new java.net.URL(url);
            java.net.URLConnection conn = teste.openConnection();
           

            java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) conn;
            httpConn.connect();
            int x = httpConn.getResponseCode();
            if (x == 200) {
                return true;
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(Internet.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (IOException ex) {
            Logger.getLogger(Internet.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
       
        return false;
    }
}

Nenhum comentário:

Postar um comentário