How do I get my Program to access the net?

Asked

Viewed 84 times

-5

I actually want to create a program that lets me know that my Internet connection is down, but I want to create it. I have some notion in java, but I wanted to know where to start.

Do I have to import any tool that accesses the net? s if the program can access the net?

Loose example here just to understand:

if (Se o acesso == true) {
    System.out.print("não faça nada");
} else {
    Comando para apitar um alarme etc???
}

1 answer

2


Try this:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ApitaQuandoCaiInternet {

    // Método que verifica se a internet está conectada.
    // Para descobrir se a internet está conectada, ele tenta conectar no google.
    public static boolean internetOk() {
        String site = "http://www.google.com";
        URL url;

        // Cria uma URL para o site do google.
        try {
            url = new URL(site);
        } catch (MalformedURLException e) {
            // Este erro não deve ocorrer nunca, pois a URL informada é sabidamente
            // bem formada. Assim sendo, lança o AssertionError que é o erro para
            // representar situações inesperadas que acredita(va)-se que nunca ocorreriam.
            throw new AssertionError(e);
        }

        HttpURLConnection c = null;
        try {

            // Abre uma conexão com o site do google.
            c = (HttpURLConnection) url.openConnection();
            c.setUseCaches(false);
            c.setRequestMethod("GET");
            c.connect();

            // Força o download de alguma resposta ao solicitar o código de status.
            // Ver https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
            // Como o propósito é apenas conectar ou não, não precisamos fazer
            // nada com o código.
            int status = c.getResponseCode();

            // Conseguiu fazer o download, estamos online.
            return true;

        // Erro no download. Estamos offline.
        } catch (IOException x) {
            return false;

        // Fecha a conexão ao final, independente do resultado.
        } finally {
            if (c != null) c.disconnect();
        }
    }

    // Método que faz um barulho.
    public static void beep() {
        java.awt.Toolkit.getDefaultToolkit().beep();
    }

    public static void main(String[] args) {
        while (true) {
            // Se a internet tiver caído, faz um barulho.
            if (!internetOk()) beep();

            // Espera 10 segundos e tenta de novo depois.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                return;
            }
        }
    }
}
  • All right, can you explain to me about the import? it looks good

  • @Den Imports are only existing libraries and classes within JDK that are used. java.net.URL is a class that, as the name says, serves to represent Urls. Already the class java.net.HttpURLConnection is the class representing an HTTP connection. java.io.IOException and java.net.MalformedURLException are some exceptions that may appear.

  • Thank you so much for the effort got top your Cod. Older I need to learn how to do this, I saw that you opened a way there and Talz.. has how to explain me step by step, I saw that because the comments.. more I have to sugar kkkk

  • understood about the libraries, more and the commands of this library?

  • example Sponse Cod?

  • @Den Since the purpose is just to connect or not, we don’t need to do anything with the code. If the status code has already been returned instead of making an exception, it is because it was able to connect. If the idea was to download or upload something, then checking the code would be important and still require several other operations, but as the purpose is just to connect, so we do not need to check the code.

  • I understood, really this is the purpose, to check if there was a connection, but, I wanted to understand about the codes you used after importing the lib ? I’m asking you because I don’t know these lib :/

  • @Den You can see all the ones on the JDK here: https://docs.oracle.com/javase/8/docs/api/ - But there are a few thousand classes. And there’s a lot you’ll find outside of JDK. To know all this it is necessary to take courses, trainings, devour books, do experiments, practice a lot and break your head. Sometimes some of these classes and methods take me years to learn how to use, and there’s certainly a lot I don’t know yet or even know exists. However, thanks to Stackoverflow and similar sites, we can share experiences to learn much faster.

  • Truth you’re absolutely right, More if not and you show me this code I wouldn’t even know about those classes, more do what right. equal the sound? I didn’t even know, if it were me, I’d send you in and start the music.mp3 kkkkkk I know those classes don’t

  • But I will study upon this code of yours,

  • and then I’m gonna swing him

  • can change the sound?

  • @Den It uses the sound configured as beep standard operating system. It can change yes, a shape (gambiarrosa) would be the start som.mp3, but surely there are better ways. I will search further, and when finished, edit the answer.

  • Ta beauty Thanks for now

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.