Checking internet connectivity in Java

Java Programming Java8Object Oriented Programming

Internet connectivity can be checked using java.net.URL and java.net.URLConnection class. Following are the required steps.

  • Create a URL object and pass it the URL say Google

  • Call URL.openConnection() method to get a URLConnection object.

  • Call URLConnection.connect() method to check the internet connectivity. connect() method opens a communications link to the resource referenced by the passed URL if a connection has not already been established.

Example

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

public class Tester {
   public static void main(String[] args) {
      try {
         URL url = new URL("http://www.google.com");
         URLConnection connection = url.openConnection();
         connection.connect();
         System.out.println("Internet is connected");
      } catch (MalformedURLException e) {
         System.out.println("Internet is not connected");
      } catch (IOException e) {
         System.out.println("Internet is not connected");
      }
   }
}

Output

Internet is connected
raja
Published on 20-Jul-2018 17:52:26
Advertisements