How to detect network breakage using java program?

后端 未结 2 1200
心在旅途
心在旅途 2020-12-22 05:02

Is there any way to detect the network breakage or weaker network, using Java?

2条回答
  •  不思量自难忘°
    2020-12-22 05:13

    you can intermittently test a http connection to a known host such as google and detect ConnectionExceptions

    URLConnection con = new URL("http://www.google.com/").openConnection();
    con.setUseCaches(false);
    con.setAllowUserInteraction(false);
    
    while(true)
    {
        try
        {
            con.connect();
            con.getContentType(); // just to make sure the connection works
            // sleep for some interval
        }
        catch(IOException e)
        {
            // handle and break
        }
    }
    

提交回复
热议问题