Java Ping URL

Chapter: Networking Last Updated: 09-08-2023 17:02:54 UTC

Program:

            /* ............... START ............... */
                

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

public class UrlPinger {
    public static void main(String[] args) {
        String urlString = "https://www.example.com"; // Replace with the URL you want to ping
        
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            
            int responseCode = connection.getResponseCode();
            System.out.println("Ping Response Code: " + responseCode);
            
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

                /* ............... END ............... */
        

Output

Ping Response Code: 200

In this example, the response code 200 indicates that the URL was successfully reached 
and the server responded with a "OK" status. The exact response code you receive could 
vary depending on the server's response and the URL you are pinging. If the URL is unreachable 
or if there's an error, you might see different response codes such as 404 (Not Found), 
500 (Internal Server Error), or other relevant codes.

Notes:

  • Replace "https://www.example.com" with the URL you want to ping. The code above creates an HTTP connection to the specified URL, sends a GET request, and then retrieves the response code from the server. This response code indicates whether the URL is reachable or not.
  • Keep in mind that this example uses the HttpURLConnection class, which is available in Java's standard library. Depending on your use case, you might also consider using libraries like Apache HttpClient or OkHttp for more advanced HTTP operations.

Tags

How to ping a URL in Java? #Java Ping URL #Java ping host

Similar Programs Chapter Last Updated
Java Socket Timeout Networking 10-12-2019
Ping IP Address In Java Example Networking 21-09-2018

1